0% found this document useful (0 votes)
25 views51 pages

Python Class Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
25 views51 pages

Python Class Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 51

Python Variables

In programming, a variable is a container (storage area) to hold data.

For example,

number = 10

Here, number is the variable storing the value 10.

Assigning values to Variables in Python


We use the assignment operator = to assign a value to a variable.

# assign value to site_name variable


site_name = 'programiz.pro'

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)

# assigning a new value to site_name


site_name = 'apple.com'

print(site_name)

Output

programiz.pro
apple.com

Here, the value of site_name is changed from 'programiz.pro' to 'apple.com' .

Example: Assigning multiple values to multiple variables

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:

site1 = site2 ='programiz.com'

print(site1) # prints programiz.com


print(site2) # prints programiz.com
We have assigned the same string value 'programiz.com' to both the

variables site1 and site2 .

Rules for Naming Python Variables


 Constant and variable names should have a combination of letters in lowercase(a to z)
or uppercase (A to Z) or digits (0 to 9) or an underscore (_).

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

 Avoid using keywords like if , True , class , etc. as variable names.


Python Constants
 A constant is a special type of variable whose value cannot be changed.
 In Python, constants are usually declared and assigned in a module (a new file
containing variables, functions, etc which is imported to the main file).
 Let's see how we declare constants in separate file and use it in the main file,

Create a constant.py:

# declare constants
PI = 3.14
GRAVITY = 9.8

Create a main.py:

# import constant file we created above


import constant

print(constant.PI) # prints 3.14


print(constant.GRAVITY) # prints 9.8

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

An expression is a combination of operators and operands that is interpreted to


produce some other value. In any programming language, an expression is evaluated
as per the precedence of its operators. So that if there is more than one operator in an
expression, their precedence decides which operation will be performed first. We have
many different types of expressions in Python.

1. Constant Expressions:

These are the expressions that have constant values only

# Constant Expressions
x =15+1.3

print(x)

Output

16.3
2. Arithmetic Expressions:

An arithmetic expression is a combination of numeric values, operators, and


sometimes parenthesis. The result of this type of expression is also a numeric value.
The operators used in these expressions are arithmetic operators like addition,
subtraction, etc. Here are some arithmetic operators in Python:

Operators Syntax Functioning

+ x+y Addition
– x–y Subtraction

* x*y Multiplication

/ x/y Division

// x // y Quotient

% x%y Remainder

** x ** y Exponentiation

Example:

Let’s see an exemplar code of arithmetic expressions in Python :

# 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:

In these types of expressions, arithmetic expressions are written on both sides


of relational operator (> ,< , >= , <=). Those arithmetic expressions are evaluated first,
and then compared as per relational operator and produce a boolean output in the end.
These expressions are also called Boolean expressions.

Example:

# Relational Expressions

a =21

b =13

c =40

d =37

p =(a +b) >=(c -d)

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:

Operator Syntax Functioning

and P and Q It returns true if both P and Q are true otherwise returns false

or P or Q It returns true if at least one of P and Q is true


not not P It returns true if condition P is false

Example:

Let’s have a look at an examplecode :

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

But when we combine different types of expressions or use multiple operators


in a single expression, operator precedence comes into play.

Multiple operators in expression (Operator Precedence)

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:

Precedence Name Operator


Precedence Name Operator

1 Parenthesis ()[]{}

2 Exponentiation **

3 Unary plus or minus, complement -a , +a , ~a

4 Multiply, Divide, Modulo / * // %

5 Addition & Subtraction + –

6 Shift Operators >> <<

7 Bitwise AND &

8 Bitwise XOR ^

9 Bitwise OR |

10 Comparison Operators >= <= > <

11 Equality Operators == !=

12 Assignment Operators = += -= /= *=
Precedence Name Operator

13 Identity and membership operators is, is not, in, not in

14 Logical Operators and, or, not

So, if we have more than one operator in an expression, it is evaluated as per


operator precedence. For example, if we have the expression “10 + 3 * 4”. Going
without precedence it could have given two different outputs 22 or 52. But now
looking at operator precedence, it must yield 22.

# 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

Hence, operator precedence plays an important role in the evaluation of a


Python expression.

What is Statement in Python

A Python statement is an instruction that the Python interpreter can


execute. There are different types of statements in Python language as
Assignment statements, Conditional statements, Looping statements, etc.

Types of statements in Python?

The different types of Python statements are listed below:


 Multi-Line Statements

 Python Conditional and Loop Statements


 Python If-else

 Python for loop

 Python while loop

 Python try-except

 Python with statement


 Python Expression statements
 Python pass statement

 Python del statement

 Python return statement

 Python import statement

 Python continue and

 Python break statement

Types of Control Flow in Python

In Python programming language, the type of control flow


statements is as follows:

 The if statement
 The if-else statement
 The nested-if statement
 The if-elif-else ladder

Python if statement

The if statement is the most simple decision-making statement. It


is used to decide whether a certain statement or block of statements will
be executed or not.

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.

Python uses indentation to identify a block. So the block under an


if statement will be identified as shown in the below example:
if condition:
statement1
statement2

# Here if the condition is true, if block


# will consider only statement1 to be inside
# its block.

Example of Python if Statement

As the condition present in the if statement is false. So, the block below the if
statement is executed.

# python program to illustrate If statement

i =10

if(i > 15):


print("10 is less than 15")

print("I am Not in if")

Output:

I am Not in if

Python If-Else Statement


The if statement alone tells us that if a condition is true it will
execute a block of statements and if the condition is false it won’t. But
if we want to do something else if the condition is false, we can use
the else statement with if statement to execute a block of code when the
if condition is false.

Syntax:

if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Flowchart of Python if-else statement

Example of Python if-else statement

The block of code following the else statement is executed as the


condition present in the if statement is false after calling the statement
which is not in the block(without spaces).

# python program to illustrate If else statement


#!/usr/bin/python

i =20

if(i < 15):

print("i is smaller than 15")

print("i'm in if Block")

else:

print("i is greater than 15")

print("i'm in else Block")

print("i'm not in if and not in else Block")

Output:

i is greater than 15

i'm in else Block

i'm not in if and not in else Block

Example of Python if else statement in a list comprehension

In this example, we are using an if statement in a list comprehension with


the condition that if the element of the list is odd then its digit sum will be stored
else not.

Nested-If Statement in Python

A nested if is an if statement that is the target of another if


statement. Nested if statements mean an if statement inside another if
statement. Yes, Python allows us to nest if statements within if
statements. i.e., we can place an if statement inside another if
statement.

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

Example of Python Nested if statement

In this example, we are showing nested if conditions in the code,


All the If conditions will be executed one by one.

# python program to illustrate nested If statement


i =10

if(i ==10):

# First if statement

if(i < 15):

print("i is smaller than 15")

# Nested - if statement

# Will only be executed if statement above

# it is true

if(i < 12):

print("i is smaller than 12 too")

else:

print("i is greater than 15")

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

Example of Python if-elif-else ladder


In the example, we are showing single if condition and multiple elif conditions,
and single else condition.

# Python program to illustrate 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:

print("i is not present")

Output:

i is 20

Short Hand if statement

Whenever there is only a single statement to be executed inside the if


block then shorthand if can be used. The statement can be put on the same line
as the if statement.
Syntax:
if condition: statement

Example of Python if shorthand


In the given example, we have a condition that if the number is less than 15,
then further code will be executed.

# Python program to illustrate short hand if

i =10

ifi < 15: print("i is less than 15")

Output:

i is less than 15

Short Hand if-else statement

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:

statement_when_True if condition else statement_when_False

Example of Python if else shorthand


In the given example, we are printing True if the number is 15 else it will
print False.

# Python program to illustrate short hand if-else

i =10

print(True) ifi < 15elseprint(False)

Output:

True

Python for Loop


In computer programming, loops are used to repeat a block of code.

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']

# run a loop for each item of the list


for language in languages:
print(language)
Run Code
Output

Swift
Python
Go
JavaScript

In the above example, we have created a list called languages .

Initially, the value of language is set to the first element of the array,i.e. Swift ,

so the print statement inside the loop is executed.


language is updated with the next element of the list, and the print statement is
executed again. This way, the loop runs until the last element of the list is
accessed.

for Loop Syntax


The syntax of a for loop is:

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

Python for Loop with Python range()


A range is a series of values between two numeric intervals.
We use Python's built-in function range() to define a range of values. For
example,

values = range(4)

Here, 4 inside range() defines a range containing values 0, 1, 2, 3.


In Python, we can use for loop to iterate over a range. For example,
# use of range() to define a range of values
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

1st True 0 is printed. i is increased to 1.

2nd True 1 is printed. i is increased to 2.

3rd True 2 is printed. i is increased to 3.


4th True 3 is printed. i is increased to 4.

5th False The loop is terminated

Note: To learn more about the use of for loop with range, visit Python range().

Using a for Loop Without Accessing Items


It is not mandatory to use items of a sequence within a for loop. For example,
languages = ['Swift', 'Python', 'Go']

for language in languages:


print('Hello')
print('Hi')
Run Code

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:

languages = ['Swift', 'Python', 'Go']


for _ in languages:
print('Hello')
print('Hi')
Run Code

The _ symbol is used to denote that the elements of a sequence will not be
used within the loop body.

Python for loop with else


A for loop can have an optional else block. The else part is executed when
the loop is exhausted (after the loop iterates through every item of a
sequence). For example,
digits = [0, 1, 5]

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)

Flowchart of While Loop :

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.

Example 1: Python While Loop



# Python program to illustrate

# while loop

count =0

while(count < 3):

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.

Example 2: Python while loop with list


# checks if list still

# contains any element

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.

Example 3: Single statement while block


Just like the if block, if the while block consists of a single statement we can
declare the entire loop in a single line. If there are multiple statements in the
block that makes up the loop body, they can be separated by semicolons (;).

# Python program to illustrate

# Single statement while block

count =0

while(count < 5): count +=1; print("Hello Geek")

Output

Hello Geek
Hello Geek
Hello Geek
Hello Geek
Hello Geek

Example 4: Loop Control Statements


Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope
are destroyed. Python supports the following control statements.
Continue Statement
Python Continue Statement returns the control to the beginning of the loop.
Example: Python while loop with continue statement

# Prints all letters except 'e' and 's'

i =0

a ='geeksforgeeks'

whilei <len(a):

ifa[i] =='e'ora[i] =='s':

i +=1

continue

print('Current Letter :', a[i])

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

# break the loop as soon it sees 'e'

# or 's'

i =0

a ='geeksforgeeks'

whilei <len(a):

ifa[i] =='e'ora[i] =='s':

i +=1

break

print('Current Letter :', a[i])

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

While loop with else

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.

# Python program to demonstrate


# while-else loop

i =0

whilei < 4:

i +=1

print(i)

else: # Executed because no break in for

print("No Break\n")

i =0

whilei < 4:

i +=1

print(i)

break

else: # Not executed as there is a break

print("No Break")

Output

1
2
3
4
No Break

Python pass Statement


In Python programming, the pass statement is a null statement which can be
used as a placeholder for future code.
Suppose we have a loop or a function that is not implemented yet, but we
want to implement it in the future. In such cases, we can use
the pass statement.
The syntax of the pass statement is:

pass

Using pass With Conditional Statement


n = 10

# use pass inside if statement


if n >10:
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).

Suppose we didn't use pass or just put a comment as:


n = 10

if n >10:
# write code later

print('Hello')
Run Code

Here, we will get an error message: IndentationError: expected an indented

block

Note: The difference between a comment and a pass statement in Python is


that while the interpreter ignores a comment entirely, pass is not ignored.

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:

 create a circle function

 create a color function

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,

 def - keyword used to declare a function


 function_name - any name given to the function
 arguments - any value passed to function
 return (optional) - returns value from a function
Let's see an example,

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.

Calling a Function in Python


In the above example, we have declared a function named greet() .
defgreet():
print('Hello World!')

Now, to use this function, we need to call it.

Here's how we can call the greet() function in Python.

# call the function


greet()

Example: Python Function


defgreet():
print('Hello World!')

# call the function


greet()

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.

 All codes inside the function are executed.


 The control of the program jumps to the next statement after the function call.

Here,

 When the function is called, the control of the program goes to the function
definition.

 All codes inside the function are executed.

 The control of the program jumps to the next statement after the function call.

Python Function Arguments


As mentioned earlier, a function can also have arguments. An argument is a
value that is accepted by a function. For example,

# function with two arguments


defadd_numbers(num1, num2):
sum = num1 + num2
print('Sum: ',sum)

# function with no argument


defadd_numbers():
# code
If we create a function with arguments, we need to pass the corresponding
values while calling them. For example,

# function call with two values


add_numbers(5, 4)

# function call with no value


add_numbers()

Here, add_numbers(5, 4) specifies that arguments num1 and num2 will get
values 5 and 4 respectively.

Example 1: Python Function Arguments


# function with two arguments
defadd_numbers(num1, num2):
sum = num1 + num2
print("Sum: ",sum)

# function call with two values


add_numbers(5, 4)

# Output: Sum: 9
Run Code

In the above example, we have created a function named add_numbers() with


arguments: num1 and num2 .
We can also call the function by mentioning the argument name as:

add_numbers(num1 = 5, num2 = 4)

In Python, we call it Keyword Argument (or named argument). The code


above is equivalent to

add_numbers(5, 4)

The return Statement in Python


A Python function may or may not return a value. If we want our function to
return some value to a function call, we use the return statement. For
example,

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.

Example 2: Function return Type


# function definition
deffind_square(num):
result = num * num
return result

# function call
square = find_square(3)

print('Square:',square)

# Output: Square: 9
Run Code

In the above example, we have created a function named find_square() . The


function accepts a number and returns the square of the number.
Example 3: Add Two Numbers
# function that adds two numbers
defadd_numbers(num1, num2):
sum = num1 + num2
return sum

# calling function with two values


result = add_numbers(5, 4)

print('Sum: ', result)

# 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,

 print() - prints the string inside the quotation marks


 sqrt() - returns the square root of a number
 pow() - returns the power of a number
These library functions are defined inside the module. And, to use them we
must include the module inside our program.

For example, sqrt() is defined inside the math module.

Example 4: Python Library Function


import math

# sqrt computes the square root


square_root = math.sqrt(4)

print("Square Root of 4 is",square_root)

# pow() comptes the power


power = pow(2, 3)

print("2 to the power 3 is",power)


Run Code

Output

Square Root of 4 is 2.0


2 to the power 3 is 8

In the above example, we have used

 math.sqrt(4) - to compute the square root of 4


 pow(2, 3) - computes the power of a number i.e. 23
Here, notice the statement,

import math

Since sqrt() is defined inside the math module, we need to include it in our
program.

Benefits of Using Functions


1. Code Reusable - We can use the same function multiple times in our
program which makes our code reusable. For example,
# function definition
defget_square(num):
returnnum * num

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.

Condition and Recursion

You might also like