Unit-2 Detailed notes
Unit-2 Detailed notes
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 .
Syntax:
if condition:
1
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
# 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
If we have only one statement to execute, we can put it on the same line as the if statement.
2
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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.
Syntax:
If condition 1 is true, we are heading towards condition 2, if not, we are heading towards condition 3
4
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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)
# 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)
5
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
# 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.
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
6
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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
Flow Chart:-
7
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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
In programming loops are structure that repeats a sequence of instruction until a specific condition is met
8
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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)
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.
9
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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
for n in x:
print(n)
Output
10
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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:
for i in range(2,10,2)
print(i)
Output:
4
11
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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:
No items left.
12
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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.
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
13
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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
Output:
14
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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’.
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:
15
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Output:
condition is true
condition is true
condition is true
condition is true
Code
count = 0
Example:
a=1
16
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
while a <5:
a += 1
if a = = 3:
break
print(a)
Output:
Example:
a=1
while a <5:
a += 1
if a = = 3:
continue
print(a)
Output:
17
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
i=1
while i <= n:
j=1
while j <= i:
print(“*”, end = “ ”)
j += 1
print()
i += 1
**
***
****
18
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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:
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)
Output:
20
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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:
21
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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])
Thu
Wed
Tue
22
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Mon
given_number = 129475
# str() function
given_number = str(given_number)
count=0
for i in given_number:
count += 1
print(count)
# given string
given_string = "madam"
23
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
reverse_string = ""
for i in given_string:
reverse_string = i + reverse_string
if(given_string = = reverse_string):
else:
given_number = 153
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:
dict = {
"one": "1",
"two": "2",
25
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
"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:
You can also use the values() function to return values of a dictionary:
dict = {
"one": "1",
"two": "2",
26
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
"three": 3
for x in dict.values():
print(x)
Output:
Loop through both keys and values, by using the items() function:
dict = {
"one": "1",
"two": "2",
"three": 3
print(x,y)
Output:
one 1
two 2
three 3
27
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
else:
if number > 1:
if (number % i) = = 0:
break
else:
28
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
else:
2,6
3,7
i=1
j=5
while i < 4:
while j < 8:
print(i, ",", j)
j=j+1
i=i+1
29