Python Class Notes
Python Class Notes
For example,
number = 10
print(site_name)
# Output: programiz.pro
In the above example, we assigned the value 'programiz.pro' to the site_name variable.
Then, we printed out the value assigned to site_name .
Note: Python is a type-inferred language, so you don't have to explicitly define the
variable type. It automatically knows that programiz.pro is a string and declares
the site_name variable as a string.
Changing the Value of a Variable in Python
site_name = 'programiz.pro'
print(site_name)
print(site_name)
Output
programiz.pro
apple.com
a, b, c = 5, 3.2, 'Hello'
print(a) # prints 5
print(b) # prints 3.2
print(c) # prints Hello
If we want to assign the same value to multiple variables at once, we can do this as:
For example:
snake_case
MACRO_CASE
camelCase
CapWords
Create a name that makes sense. For example, vowel makes more sense than v .
If you want to create a variable name having two words, use underscore to separate
them.
For example:
my_name
current_salary
Python is case-sensitive. So num and Num are different variables. For example,
num = 5
Num = 55
print(num) # 5
print(Num) # 55
Create a constant.py:
# declare constants
PI = 3.14
GRAVITY = 9.8
Create a main.py:
we created the constant.py module file. Then, we assigned the constant value
to PI and GRAVITY .
After that, we create the main.py file and import the constant module. Finally,
we printed the constant value.
Note: In reality, we don't use constants in Python. Naming them in all capital letters
is a convention to separate them from variables, however, it does not actually prevent
reassignment.
Expressions in Python
1. Constant Expressions:
# Constant Expressions
x =15+1.3
print(x)
Output
16.3
2. Arithmetic Expressions:
+ x+y Addition
– x–y Subtraction
* x*y Multiplication
/ x/y Division
// x // y Quotient
% x%y Remainder
** x ** y Exponentiation
Example:
# Arithmetic Expressions
x =40
y =12
add =x +y
sub =x -y
pro =x *y
div =x /y
print(add)
print(sub)
print(pro)
print(div)
Output
52
28
480
3.3333333333333335
3. Integral Expressions:
These are the kind of expressions that produce only integer results after all
computations and type conversions.
Example:
# Integral Expressions
a =13
b =12.0
c =a +int(b)
print(c)
Output
25
4. Floating Expressions:
These are the kind of expressions which produce floating point numbers as result after
all computations and type conversions.
Example:
# Floating Expressions
a =13
b =5
c =a /b
print(c)
Output
2.6
5. Relational Expressions:
Example:
# Relational Expressions
a =21
b =13
c =40
d =37
print(p)
Output
True
6. Logical Expressions:
These are kinds of expressions that result in either True or False. It basically
specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal
to 9. As we know it is not correct, so it will return False. Studying logical expressions,
we also come across some logical operators which can be seen in logical expressions
most often. Here are some logical operators in Python:
and P and Q It returns true if both P and Q are true otherwise returns false
Example:
P =(10==9)
Q =(7> 5)
# Logical Expressions
R =P andQ
S =P orQ
T =notP
print(R)
print(S)
print(T)
Output
False
True
True
7. Bitwise Expressions:
These are the kind of expressions in which computations are performed at bit
level.
Example:
# Bitwise Expressions
a =12
x =a >> 2
y =a << 1
print(x, y)
Output
3 24
8. Combinational Expressions:
We can also use different types of expressions in a single expression, and that
will be termed as combinational expressions.
Example:
# Combinational Expressions
a =16
b =12
c =a +(b >> 1)
print(c)
Output
22
It’s a quite simple process to get the result of an expression if there is only one
operator in an expression. But if there is more than one operator in an expression, it
may give different results on basis of the order of operators executed. To sort out
these confusions, the operator precedence is defined. Operator Precedence simply
defines the priority of operators that which operator is to be executed first. Here we
see the operator precedence in Python, where the operator higher in the list has more
precedence or priority:
1 Parenthesis ()[]{}
2 Exponentiation **
8 Bitwise XOR ^
9 Bitwise OR |
11 Equality Operators == !=
12 Assignment Operators = += -= /= *=
Precedence Name Operator
# Multi-operator expression
a =10+3*4
print(a)
b =(10+3) *4
print(b)
c =10+(3*4)
print(c)
Output
22
52
22
Python try-except
The if statement
The if-else statement
The nested-if statement
The if-elif-else ladder
Python if statement
Syntax:
ifcondition:
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if
the statement accepts boolean values – if the value is true then it will
execute the block of statements below it otherwise not.
As the condition present in the if statement is false. So, the block below the if
statement is executed.
i =10
Output:
I am Not in if
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Flowchart of Python if-else statement
i =20
print("i'm in if Block")
else:
Output:
i is greater than 15
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Flowchart of Python Nested if Statement
if(i ==10):
# First if statement
# Nested - if statement
# it is true
else:
Output:
i is smaller than 15
i is smaller than 12 too
Python if-elif-else Ladder
The if statements are executed from the top down. As soon as one
of the conditions controlling the if is true, the statement associated with
that if is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed.
Syntax:
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Flowchart of Python if-elif-else ladder
#!/usr/bin/python
i =20
if(i ==10):
print("i is 10")
elif(i ==15):
print("i is 15")
elif(i ==20):
print("i is 20")
else:
Output:
i is 20
i =10
Output:
i is less than 15
This can be used to write the if-else statements in a single line where only
one statement is needed in both the if and else blocks.
Syntax:
i =10
Output:
True
For example, if we want to show a message 100 times, then we can use a
loop. It's just a simple example; you can achieve much more with loops.
There are 2 types of loops in Python:
for loop
while loop
Python for Loop
In Python, a for loop is used to iterate over sequences such
as lists, tuples, string, etc. For example,
languages = ['Swift', 'Python', 'Go', 'JavaScript']
Swift
Python
Go
JavaScript
Initially, the value of language is set to the first element of the array,i.e. Swift ,
forvalin sequence:
# statement(s)
Here, val accesses each item of sequence on each iteration. The loop
continues until we reach the last item in the sequence.
Example:
Loop Through a String
for x in'Python':
print(x)
Run Code
Output
P
y
t
h
o
n
values = range(4)
# iterate from i = 0 to i = 3
for i in values:
print(i)
Run Code
Output
0
1
2
3
In the above example, we have used the for loop to iterate over a range
from 0 to 3.
The value of i is set to 0 and it is updated to the next number of the range on
each iteration. This process continues until 3 is reached.
Iteration Condition Action
Note: To learn more about the use of for loop with range, visit Python range().
Output
Hello
Hi
Hello
Hi
Hello
Hi
Here, the loop runs three times because our list has three items. In each
iteration, the loop body prints 'Hello' and 'Hi' . The items of the list are not
used within the loop.
If we do not intend to use items of a sequence within the loop, we can write
the loop like this:
The _ symbol is used to denote that the elements of a sequence will not be
used within the loop body.
for i in digits:
print(i)
else:
print("No items left.")
Run Code
Output
0
1
5
No items left.
Here, the for loop prints all the items of the digits list. When the loop finishes,
it executes the else block and prints No items left.
Note: The else block will not execute if the for loop is stopped by
a break statement.
Python While Loop
Python While Loop is used to execute a block of statements repeatedly until a
given condition is satisfied. And when the condition becomes false, the line
immediately after the loop in the program is executed.
Syntax:
while expression:
statement(s)
While loop falls under the category of indefinite iteration. Indefinite iteration
means that the number of times the loop is executed isn’t specified explicitly in
advance.
Statements represent all the statements indented by the same number of
character spaces after a programming construct are considered to be part of a
single block of code. Python uses indentation as its method of grouping
statements. When a while loop is executed, expr is first evaluated in a Boolean
context and if it is true, the loop body is executed. Then the expr is checked
again, if it is still true then the body is executed again and this continues until
the expression becomes false.
# while loop
count =0
count =count +1
print("Hello Geek")
Output
Hello Geek
Hello Geek
Hello Geek
In the above example, the condition for while will be True as long as the counter
variable (count) is less than 3.
a =[1, 2, 3, 4]
whilea:
print(a.pop())
Output
4
3
2
1
In the above example, we have run a while loop over a list that will run until
there is an element present in the list.
count =0
Output
Hello Geek
Hello Geek
Hello Geek
Hello Geek
Hello Geek
i =0
a ='geeksforgeeks'
whilei <len(a):
i +=1
continue
i +=1
Output
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
Break Statement
Python Break Statement brings control out of the loop.
Example: Python while loop with a break statement
# or 's'
i =0
a ='geeksforgeeks'
whilei <len(a):
i +=1
break
i +=1
Output
Current Letter : g
Pass Statement
The Python pass statement to write empty loops. Pass is also used for empty
control statements, functions, and classes.
Example: Python while loop with a pass statement
# An empty loop
a ='geeksforgeeks'
i =0
whilei <len(a):
i +=1
pass
print('Value of i :', i)
Output
Value of i : 13
As discussed above, while loop executes the block until a condition is satisfied.
When the condition becomes false, the statement immediately after the loop is
executed. The else clause is only executed when your while condition becomes
false. If you break out of the loop, or if an exception is raised, it won’t be
executed.
Note: The else block just after for/while is executed only when the loop is NOT
terminated by a break statement.
i =0
whilei < 4:
i +=1
print(i)
print("No Break\n")
i =0
whilei < 4:
i +=1
print(i)
break
print("No Break")
Output
1
2
3
4
No Break
pass
print('Hello')
Run Code
Here, notice that we have used the pass statement inside the if statement.
However, nothing happens when the pass is executed. It results in no
operation (NOP).
if n >10:
# write code later
print('Hello')
Run Code
block
Python Functions
A function is a block of code that performs a specific task.
Suppose, you need to create a program to create a circle and color it. You can
create two functions to solve this problem:
Dividing a complex problem into smaller chunks makes our program easy to
understand and reuse.
Types of function
There are two types of function in Python programming:
Standard library functions - These are built-in functions in Python that are
available to use.
User-defined functions - We can create our own functions based on our
requirements.
Python Function Declaration
The syntax to declare a function is:
deffunction_name(arguments):
# function body
return
Here,
defgreet():
print('Hello World!')
Here, we have created a function named greet() . It simply prints the text Hello
World! .
This function doesn't have any arguments and doesn't return any values. We
will learn about arguments and return statements later in this tutorial.
print('Outside function')
Run Code
Output
Hello World!
Outside function
In the above example, we have created a function named greet() . Here's how
the program works:
Here,
When the function is called, the control of the program goes to the function
definition.
Here,
When the function is called, the control of the program goes to the function
definition.
The control of the program jumps to the next statement after the function call.
Here, add_numbers(5, 4) specifies that arguments num1 and num2 will get
values 5 and 4 respectively.
# Output: Sum: 9
Run Code
add_numbers(num1 = 5, num2 = 4)
add_numbers(5, 4)
defadd_numbers():
...
return sum
Here, we are returning the variable sum to the function call.
Note: The return statement also denotes that the function has ended. Any
code after return is not executed.
# function call
square = find_square(3)
print('Square:',square)
# Output: Square: 9
Run Code
# Output: Sum: 9
Run Code
Python Library Functions
In Python, standard library functions are the built-in functions that can be used
directly in our program. For example,
Output
import math
Since sqrt() is defined inside the math module, we need to include it in our
program.
for i in [1,2,3]:
# function call
result = get_square(i)
print('Square of',i, '=',result)
Run Code
Output
Square of 1 = 1
Square of 2 = 4
Square of 3 = 9
In the above example, we have created the function named get_square() to
calculate the square of a number. Here, the function is used to calculate the
square of numbers from 1 to 3.
Hence, the same method is used again and again.
2. Code Readability - Functions help us break our code into chunks to make
our program readable and easy to understand.