[Go to site: main page, start]

0% found this document useful (0 votes)
92 views20 pages

Python Basics: Variables, Loops, and Functions

This document provides an overview of key Python concepts including variables, data types, strings, arithmetic operators, conditional statements, loops, lists, tuples, dictionaries, functions, classes and exceptions. It defines variables, demonstrates printing, input functions, and the type() function. It also covers string indexing, slicing, methods and concatenation. Arithmetic operators, if/else statements, logical operators and comparison operators are defined. While and for loops are demonstrated along with examples. Lists, tuples and dictionaries are also introduced.

Uploaded by

Vannila
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views20 pages

Python Basics: Variables, Loops, and Functions

This document provides an overview of key Python concepts including variables, data types, strings, arithmetic operators, conditional statements, loops, lists, tuples, dictionaries, functions, classes and exceptions. It defines variables, demonstrates printing, input functions, and the type() function. It also covers string indexing, slicing, methods and concatenation. Arithmetic operators, if/else statements, logical operators and comparison operators are defined. While and for loops are demonstrated along with examples. Lists, tuples and dictionaries are also introduced.

Uploaded by

Vannila
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Basics

variable:
irshath = ‘hello world’

printing in python:
print(‘hello world’)

getting input in python:


input(‘Enter your name’)
note:
the default datatype in input function is string.
if you are going to enter a string
input(“Enter your name”)
if you are going to enter integer(number)
int(input(‘Enter your phone number’))
if you are going to enter a bool (i.e) True / False
bool(input(“True/False”))

type function:
type function is used to get the datatype of a variable. it will tell you what datatype
the variable is like int, string, bool , etc..
eg:
number = 10;
print(type(number))
output: <class int>
strings:
you can use either “” or ‘’ for strings
there is another way to define a string
is ‘’’
eg:
print(‘irshath’)
print(“irshath”)
print(‘’’Hello I’m irshath ‘’’)
you can use ‘’’ triple times to define a string

to get a single letter of a string

just type the index of the string to get the output

to get from a particular letter to particular letter from a string


name = irshath
print(name[0:3])
output:
irsh

string concatenation:
you can add strings in python
eg:
first_name = "mohammed "
last_name = "irshath"
print(first_name + last_name + "is a coder")

you can insert a variable in between a string

first_name = "mohammed "
last_name = "irshath"
print(f"{first_name} {last_name} is a coder")

you should use a keyword f in the starting to do that


print(f"{first_name} {last_name} is a coder")

String methods:
there are many many string methods are there in python. some of them are given
below.
name = "irshath"
print(len(name)) – used to check total no of letters
print([Link]()) – changes to UPPERCASE
print([Link]()) -changes to lowercase
print([Link]("i")) – finds and prints the index of the string which you enter in the
parameter
print([Link]("irshath", "arshath")) – replaces the string
finding = "irshath" in name
print(finding) – checks whether the string is available or not. if available it prints
True, if not availabe prints False

Examples of all the above Methods


arithmetic operators:
10 + 10 = 20 addition
10 – 10 = 0 subtraction
10 * 10 = 100 multiplication
10 / 3 = 3.333 division
10 // 3 = 3 it is also division but it will omit the decimal numbers and returns always
the whole number
10 % 3 = 1 returns the remainder of the division
10 ** 3 = 1000 square root (i.e) it is the square value 10 X 10 X 10

short form for add sub mul div in modifying a variable:


Long code
x = 10
x=x+3
short form
x+=3
x-=3
x*=3
x/=3
like this you can shorter the code
this shows what operations will be execute first(first priority)
first 1. parenthesis()
[Link] 2**3
3. multiplication or division
4. addition or subtraction

numeric functions(methods)
there are lot of functions to perform numeric operations in python. you can google it
and refer them. some of them are given below
import math

number = 2.5
print([Link](number))
print([Link](number))

output:
3
2
ceil rounds the decimal number to whole number which increases in greater format
floor does the same but it will decrease

if statement:
weather = input("how is the climate today: ")
hot = "hot"
cold = "cold"
if weather == cold:
    print("It's a cold day")
    print("Wear warm clothes")
elif weather == hot:
    print("It's a hot day")
    print("Drink plenty of water")
else:
    print("It's a lovely day")
logical operator:
and – executes when both element or variable is true
or – executes if one of the element is true
not – reverse the answer if you use not operator, if the element is true it will make it
false and vice versa

eg:
high_income = True
good_credit = False

if high_income or good_credit:
    print("Eligible for loan")
else:
    print("Not Eligible")

Comparison operator:
>
<
==
>=
<=
!=
etc..

Some Example:
import math

print("Weight Converter")
weight = input("Enter your weight: ")
typeOfWeight = input("Enter Pounds or Kilogram: ")
pounds = "pounds"
kilo = "kilogram"
toPounds = [Link](int(weight) * 2.20)
toKilo = [Link](int(weight) / 2.20)
if typeOfWeight == kilo:
    print(f"You are {toPounds} Pounds")
elif typeOfWeight == pounds:
    print(f"You are {toKilo} kilos")

while loop:
syntax:
while condition:
print()
i++

example:
# guessing game

correctGuess = 7
i = 0
while i < 3:
    guess = int(input("Guess: "))
    i += 1
    if guess == correctGuess:
        print("You guessed it right")
        break
    else:
        print("Try again")
else:
    print("Sorry you're failed")

Note:

always use i+=1 when using while statement


while also has else statement. else will be executed when the loop completely
executed.
break is used to exit the loop
for loop:

List(array) in python
syntax:
list = [1, 2, 3, 4]

list methods:
there are lots of list methods in python just google them
eg:
append(), clear(), push()
just a code to remove repeated number
tuple:
it is same like list but you cannot modify tuple. list can be modified but tuple cant
syntax:
names = (irshath, arshath, umar)

dictionaries:
functions:
exception handling:

comments:
#this is a comment
Class:
classes are like objects . it is very important in oop(object oriented programming)
Syntax:
class IrshathClass:
..........

Note:
the first letter of class name should be capital eg: class Arshath:
after creating class
we should create a variable and type the object eg: ClassName()

constructor:
use
def __init__(self):
to create a constructor

inheritance:
inheritance is called reusability. reusing the code from the parent class is called
inheritance
you can reuse the code used in a class without copying. you just refer the name of
the class to the new class to reuse them. these type of reusing is called inheritance

modules:
modules are python files (i.e) [Link]

you can import modules syntax given below


import app
python file name
you can also import a specific function or method in python
from app import irshathFunc
packages or directories:
packages or directories are called folders where the python files are available

if you want to create a new folder and paste all the python files you should follow
the below rule

step1: create a new folder


step2: after creating open that folder and do the following
__init__.py
you should type this python file as exactly as this to make your folder work
it is like showing python that it is a folder for creating python files
step3: now you can create your python files in the new folder

if you want to import a python file which is located in a different folder you can do
that by doing the following
import [Link]

folder name python file name

Common questions

Powered by AI

Python follows operator precedence rules, ensuring certain operations are performed before others in mathematical expressions. Parentheses take the highest precedence, followed by exponentiation (**), then multiplication/division, and finally addition/subtraction . This hierarchy can affect outcomes; for instance, '3 + 5 * 2' results in 13 because multiplication precedes addition .

Arithmetic operators in Python allow for clear and concise expressions of mathematical operations, reducing code complexity and potential errors . For example, using the operator '10 + 10' directly equals 20 as opposed to manually stepping through the addition process. This simplification is essential for readability and preventing arithmetic mistakes in code .

String methods in Python provide functions for common tasks such as changing character case (upper, lower), finding substrings, replacing substrings, and checking for the presence of characters . These methods enhance programming by enabling efficient and concise string operations without requiring manual implementation .

Lists in Python are mutable, allowing changes to their elements, whereas tuples are immutable, which means their elements cannot be altered once set . Lists afford flexibility in data handling, suitable for dynamic collections which may need modification, while tuples offer predictability and performance benefits by preventing unintended changes .

Inheritance in Python allows a new class (child) to reuse methods and properties from an existing class (parent), fostering code reusability and reducing redundancy . For instance, a 'Vehicle' class might have attributes like 'wheels' and methods like 'move'; a 'Car' class can inherit from 'Vehicle', utilizing these properties while adding specific features like 'isConvertible' .

Modules in Python are single files containing code, such as functions or classes, that can be imported into other programs to provide functionality . Packages are collections of modules, organized into directories, which include a special __init__.py file to signal Python that the directory should be treated as a package . Modules streamline code reuse, while packages allow for better organization of related modules into cohesive, manageable sets .

Break allows for immediate termination of a loop, providing control over loop execution when predefined conditions are met, thus preventing unnecessary iterations . The else statement executes when a while loop completes naturally, without hitting a break statement, aiding in distinguishing between regular completion and premature exits . These enhance loop functionality and control .

F-strings provide a more readable and efficient way to format strings compared to manual concatenation. They allow embedding expressions inside string literals, enclosed in curly braces, which simplifies the syntax and improves code maintainability . Manual concatenation using the '+' operator can make the code less readable and more error-prone, especially with complex expressions .

Conditional statements in Python, primarily if-elif-else constructs, allow programs to execute certain blocks of code based on logical conditions . For example, a weather application might use these to respond differently to climate input: 'if weather == "cold": print("It's a cold day")' would execute when the weather is 'cold', guiding users to dress warmly .

In Python, the input function returns data as a string by default even if the input is numeric or boolean in nature . To handle numeric or boolean data types, you must explicitly convert the input using functions like int() for integers or bool() for boolean values .

You might also like