Unit2 Python
Unit2 Python
Conditional execution:
Normal flow of execution is sequential means they execute one statement after another in the order in
which they appear and stop when they sun out of statement. But a there may be a situation where the
execution of a statement or block of statement is based on some conditions.
Decision-making statements in programming languages decide the direction (Control Flow) of the flow of
program execution.
1. The if statement
2. The if-else statement
3. The nested-if statement
4. The if-elif-else ladder
Python if statement:
The if statement is the simplest decision-making statement. It is used to decide whether a certain
statement or block of statements will be executed or not .
1
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Syntax:
if condition:
# 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.
The Boolean expression after if is called the condition. If it is true, then the indented statement gets
executed. If not, nothing happens.
Ex:
a = 33
b = 200
if b > a:
print("b is greater than a")
Note:
A few important things to note about if statements:
1. The colon (:) is significant and required. It separates the header of the compound statement from
the body.
2. The line after the colon must be indented. It is standard in Python to use four spaces for indenting.
3. All lines indented the same amount after the colon will be executed whenever
BOOLEAN_EXPRESSION is true
2
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
If we have only one statement to execute, we can put it on the same line as the if statement.
if statements cannot be empty, but if you for some reason have an if statement with no content, put in
the pass statement to avoid getting an error.
a = 33
b = 200
if b > a:
pass
A second form of the if statement is alternative execution, in which there are two possibilities and the
condition determines which one gets executed.
There are two possibilities and the condition determines which one gets executed.
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:
# condition is true
else:
# condition is false
3
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Ex:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
If we have only one statement to execute, one for if, and one for else, we can put it all on the same line:
a=2
b = 330
print("A") if a > b else print("B")
We can also use an if statement inside of an if statement. This is known as a nested if statement.
4
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Syntax:
If condition 1 is true, we are heading towards condition 2, if not, we are heading towards condition 3
If condition 2 is true, the statement A will be executed, if not, the statement B will be executed.
After the end of the nested if else blocks, the rest of the code, i.e., the statement X will be executed
statement_X...
Syntax:
if condition_1:
if condition_2:
statement_A...
else:
statement_B...
else:
statement_ C...
Statement_X
# If a is greater than b
if a > b:
# If b is greater than c
if a > c:
print("The greatest number among the three is",a)
5
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
# If b is greater than c
if b > c:
# If b is greater than a
if b > a:
print("The greatest number among the three is",a)
# If c is greater than a
if c > a:
# If c is greater than b
if c > b:
print("The greatest number among the three is",a)
A leap year occurs in each year which is an integer multiple of 4 and if the year is also a multiple
of 100, it should also be a multiple of 400 to be a leap year.
if-elif Statement
The if-elif statement is shortcut of if..else chain. While using if-elif statement at the end else block
is added which is performed if none of the above if-elif statement is true.
6
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
When there is more than just two if conditions in if elif else statements, then it is referred to as if elif else
ladder, as it resembles the structure of a ladder in terms of if statements. If one of the if conditions turn out
to be true, then the rest of the ladder is just bypassed and the body of that particular if block is executed. If
all the if conditions turn out to be false, then the body of the last else block is executed.
Syntax: -
if condition-1:
statement1
elif condition-2:
statement2
. elif condition-3:
Statement3
elif condition-n
Statement-n
.else:
default statement
next statement
7
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Flow Chart:-
a= 50
if (a == 20):
print (“value of variable a is 20”)
elif (a == 30):
print (“value of variable a is 30”)
elif (a == 40):
print (“value of variable a is 40”)
else:
print (“value of variable a is greater than 40”)
Output:
value of variable a is greater than 40
8
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
In programming loops are structure that repeats a sequence of instruction until a specific condition is met
In Python, the for loop is often used to iterate over iterable objects such as lists, tuples, or strings.
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string) .
If we have a section of code that we would like to repeat a certain number of times, we employ for loops.
The for-loop is usually used on an iterable object such as a list or the in-built range function.
Statement(s)
9
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
The first item (at 0th index) in the sequence is assigned to the iterating variable iterating_var.
Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the
statement(s) block is executed until the entire sequence is exhausted.
As in flowchart, the loop will continue to execute until the last item in the sequence is reached.
sum = 0
Output:
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and stops before a specified number.
Syntax
Parameter Values
Parameter Description
Start Optional. An integer number specifying at which position to
start. Default is 0
Stop Required. An integer number specifying at which position to stop
(not included). Goes till stop-1
Step Optional. An integer number specifying the incrementation.
Default is 1
10
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
for n in x:
print(n)
Output
5
7
9
We can specify a particular range using an inbuilt Python function, named range(), to iterate the loop a
specified number of times through that range.
for i in range(2,10):
print(i)
Output:
By default, the increment in the range() function when used with loops is set to 1;
However, we can change or specify a particular increment by including a third parameter in the range()
function, as illustrated in the following example:
11
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
for i in range(2,10,2)
print(i)
Output:
for x in "banana":
print(x)
Output:
b
a
n
a
n
a
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:
12
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
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.
For example,
print('Hello')
print('Hi')
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.
13
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
While loop statements in Python are used to repeatedly execute a certain statement as long as the
condition provided in the while loop statement stays true. While loops let the program control to iterate
over a block of code.
while test_expression:
body of while
The program first evaluates the while loop condition. If it’s true, then the program enters the loop and
executes the body of the while loop. It continues to execute the body of the while loop as long as the
condition is true. When it is false, the program comes out of the loop and stops repeating the body of the
while loop.
a=1
while a<10:
a = a+1
14
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Output:
Infinite while loop refers to a while loop where the while condition never becomes false. When a
condition never becomes false, the program enters the loop and keeps repeating that same block of code
over and over again, and the loop never ends.
a=1
while a==1:
If we run the above code block, it will execute an infinite loop that will ask for our names again and again.
The loop won’t break until we press ‘Ctrl+C’.
15
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
In Python, we can also use the else statement with loops. When the else statement is used with the while
loop, it is executed only if the condition becomes false.
a=1
while a<5:
print(“condition is true”)
a=a+1
else:
Output:
condition is true
condition is true
condition is true
condition is true
Code
count = 0
16
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Example:
a=1
while a <5:
a += 1
if a = = 3:
break
print(a)
Output:
Example:
a=1
while a <5:
a += 1
if a = = 3:
17
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
continue
print(a)
Output:
18
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
i=1
while i <= n:
j=1
while j <= i:
print(“*”, end = “ ”)
j += 1
print()
i += 1
**
***
****
19
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
fac = 1
i=1
fac = fac * i
i=i+1
Enter a number: 4
Factorial of 4 is 24
Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for classes, functions, and
empty control statements.
Code
pass
Output:
Last Letter:
20
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
1. break Statement
Just as in while loops, for loops can also be prematurely terminated using the break statement. The break
statement will immediately terminate the execution of the loop and transfer the control of the program to
the end of the loop.
Example:
number_list = [2,3,4,5,6,7,8]
for i in number_list:
print(i)
if i == 5:
break
Output:
2. Continue Statement
Just as with while loops, the continue statement can also be used in Python for loops to terminate the
ongoing iteration and transfer the control to the beginning of the loop to continue the next iteration.
number_list = [2,3,4,5,6,7,8]
for i in number_list:
if i = = 5:
continue
print(i)
21
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Output:
For loop in Python can have an optional else block. The else block will be executed only when all
iterations are completed. When break is used in for loop to terminate the loop before all the iterations are
completed, the else block is ignored.
Example:
for i in range(1,6):
print(i)
else:
Output:
22
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
As the name suggests, nested loops are the loops that are nested inside an existing loop, that is, nested
loops are the body of another loop.
Example:
for i in range(1,9,2):
for j in range(i):
print()
Output:
333
55555
7777777
We can reverse for loop in python in two ways. The first method is to use the reversed() function.
for i in reversed(list) :
print(i)
print(list[i])
23
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Thu
Wed
Tue
Mon
given_number = 129475
# str() function
given_number = str(given_number)
count=0
for i in given_number:
count += 1
print(count)
24
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
# given string
given_string = "madam"
reverse_string = ""
for i in given_string:
reverse_string = i + reverse_string
if(given_string = = reverse_string):
else:
given_number = 153
25
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
given_number = str(given_number)
string_length = len(given_number)
# each digit
sum = 0
for i in given_number:
sum += int(i)**string_length
if sum == int(given_number):
else:
26
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
dict = {
"one": "1",
"two": "2",
"three": 3
for x in dict:
print(x)
Output:
one
two
three
dict = {
"one": "1",
"two": "2",
"three": 3
for x in dict:
print(dict[x])
Output:
27
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
You can also use the values() function to return values of a dictionary:
dict = {
"one": "1",
"two": "2",
"three": 3
for x in [Link]():
print(x)
Output:
Loop through both keys and values, by using the items() function:
dict = {
"one": "1",
"two": "2",
"three": 3
print(x,y)
28
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Output:
one 1
two 2
three 3
29
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
else:
if number > 1:
if (number % i) = = 0:
break
else:
else:
30
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
2,6
3,7
i=1
j=5
while i < 4:
while j < 8:
print(i, ",", j)
j=j+1
i=i+1
31