--------------------------------------------------------------------
------------------------------------------------------------
Unit 4:
Conditonal and Looping Statement (Flow control)
--------------------------------------------------------------------
------------------------------------------------------------
Conditional Statements and Looping Statements
also called flow control statements
Flow control describes the order in which statements will be
executed at runtime.
Flow control statements are divided into three categoriesin Python
1. if Statement :
Before going to discuss about if statement syntax and examples, we
need to know about an important concept known as indentation.
if condition: (Note: In Python any where we are using colon(:) means we are defining block)
.......statement 1
.......statement 2 (These statements are said to be same indentation)
.......statement 3
statement 4 (This statement is not under if statement)
If you are not followed indentation, you will get indentation
error.
Example
In [1]: if 10<20:
print('10 is less than 20')
print('End of Program')
10 is less than 20
End of Program
In [2]: # if indentation is not followed, Python will raise error
if 10<20:
print('10 is less than 20')
print('End of Program')
Cell In[2], line 4
print('10 is less than 20')
^
IndentationError: expected an indented block
In [1]: name=input("Enter Name:")
if name=="Uppu":
print("Hello upendra Good Morning")
print("How are you!!!")
Enter Name:Uppu
Hello upendra Good Morning
How are you!!!
if - else Statement:
Syntax
if condition:
........ Action 1
else:
........ Action 2
if condition is true then Action-1 will be executed otherwise Action-2 will be executed.
Example
In [6]: name = input('Enter Name : ')
if name == 'Uppu':
print('Hello Upendra! Good Morning')
else:
print('Hello Guest! Good MOrning')
print('How are you?')
Enter Name : Uppu
Hello Upendra! Good Morning
How are you?
if-elif-else Statement:
Syntax
if condition1:
........ Action-1
elif condition2:
........ Action-2
elif condition3:
........ Action-3
elif condition4:
........ Action-4
........ ...
else:
........ Default Action
Based condition the corresponding action will be executed.
In [10]: brand=input("Enter Your Favourite Brand among Amul, Dabur, KFC:")
if brand=="Amul":
print("You must be liking dairy product ")
elif brand=="Dabur":
print("You must be liking chawanprash ")
elif brand=="KFC":
print("You eat non-veg Chiiiiiiiiiii")
else :
print("Other Brands are not recommended")
Enter Your Favourite Brand among Amul, Dabur, KFC:KFC
You eat non-veg Chiiiiiiiiiii
Q 1. Write a program to find biggest of given 2 numbers.
In [11]: n1=int(input("Enter First Number:"))
n2=int(input("Enter Second Number:"))
if n1>n2:
print("Biggest Number is:",n1)
else :
print("Biggest Number is:",n2)
Enter First Number:45
Enter Second Number:35
Biggest Number is: 45
Q 2. Write a program to find biggest of given 3 numbers
In [12]: n1=int(input("Enter First Number:"))
n2=int(input("Enter Second Number:"))
n3=int(input("Enter Third Number:"))
if n1>n2 and n1>n3:
print("Biggest Number is:",n1)
elif n2>n3:
print("Biggest Number is:",n2)
else :
print("Biggest Number is:",n3)
Enter First Number:12
Enter Second Number:54
Enter Third Number:25
Biggest Number is: 54
Q 3. Write a program to find smallest of given 2 numbers?
In [13]: n1=int(input("Enter First Number:"))
n2=int(input("Enter Second Number:"))
if n1>n2:
print("Smallest Number is:",n2)
else :
print("Smallest Number is:",n1)
Enter First Number:42
Enter Second Number:85
Smallest Number is: 42
Q 4. Write a program to find smallest of given 3 numbers?
In [14]: n1=int(input("Enter First Number:"))
n2=int(input("Enter Second Number:"))
n3=int(input("Enter Third Number:"))
if n1<n2 and n1<n3:
print("Smallest Number is:",n1)
elif n2<n3:
print("Smallest Number is:",n2)
else :
print("Smallest Number is:",n3)
Enter First Number:47
Enter Second Number:78
Enter Third Number:95
Smallest Number is: 47
Q 5. Write a program to check whether the given number is
even or odd?
In [ ]:
In [15]: n1=int(input("Enter First Number:"))
rem = n1 % 2
if rem == 0:
print('Entered Number is an Even Number')
else:
print('Entered Number is an Odd Number')
Enter First Number:465
Entered Number is an Odd Number
Q 6. Write a program to check whether the given number is
in between 1 and 100?
In [16]: n=int(input("Enter Number:"))
if n>=1 and n<=100 :
print("The number",n,"is in between 1 to 100")
else:
print("The number",n,"is not in between 1 to 100")
Enter Number:454
The number 454 is not in between 1 to 100
Q 7. Write a program to take a single digit number from the
key board and print it's value in English word?
In [17]: n=int(input("Enter a digit from o to 9:"))
if n==0 :
print("ZERO")
elif n==1:
print("ONE")
elif n==2:
print("TWO")
elif n==3:
print("THREE")
elif n==4:
print("FOUR")
elif n==5:
print("FIVE")
elif n==6:
print("SIX")
elif n==7:
print("SEVEN")
elif n==8:
print("EIGHT")
elif n==9:
print("NINE")
else:
print("PLEASE ENTER A DIGIT FROM 0 TO 9")
Enter a digit from o to 9:5
FIVE
Another Way of writing above program for the same requirement
In [18]: list1 = ['ZERO','ONE','TWO','THREE','FOUR','FIVE','SIX','SEVEN','EIGHT','NINE']
n =int(input('Enter a digit from 0 to 9 :'))
print(list1[n])
Enter a digit from 0 to 9 :4
FOUR
2. Iterative Statements
If we want to execute a group of statements multiple times then we should go for Iterative statements.
Python supports 2 types of iterative statements.
1. for loop
2. while loop
1. for loop:
If we want to execute some action for every element present in some sequence (it may be string or
collection) then we should go for for loop.
Syntax:
for x in sequence:
....... body
where 'sequence' can be string or any collection.
Body will be executed for every element present in the sequence.
Q 1. Write a Program to print characters present in the given
string.
In [20]: s="India"
for x in s :
print(x)
I
n
d
i
a
Q 2: To print characters present in string index wise.
In [21]: s=input("Enter some String: ")
i=0
for x in s :
print("The character present at ",i,"index is :",x)
i=i+1
Enter some String: upendra
The character present at 0 index is : u
The character present at 1 index is : p
The character present at 2 index is : e
The character present at 3 index is : n
The character present at 4 index is : d
The character present at 5 index is : r
The character present at 6 index is : a
Q 3: To print Hello 10 times.
In [22]: s = 'Hello'
for i in range(1,11):
print(s)
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Q 4: To display numbers from 0 to 10
In [23]: for i in range(0,11):
print(i)
0
1
2
3
4
5
6
7
8
9
10
Q5 To display odd numbers from 0 to 20
In [24]: for i in range(21):
if(i%2!=0):
print(i)
1
3
5
7
9
11
13
15
17
19
Q6: To display numbers from 10 to 1 in descending order
In [25]: for i in range(10,0,-1):
print(i)
10
9
8
7
6
5
4
3
2
1
Q7: To print sum of numbers presenst inside list.
In [31]: list=eval(input("Enter List:"))
sum=0;
for x in list:
sum=sum+x;
print("The Sum=",sum)
Enter List:45,78,96
The Sum= 219
while loop:
If we want to execute a group of statements iteratively until some condition false,then we should go for
while loop.
Syntax:
while condition:
........ body
Q1: To print numbers from 1 to 10 by using while loop
In [33]: x=1
while x <=10:
print(x)
x=x+1
1
2
3
4
5
6
7
8
9
10
Q 2: To display the sum of first n numbers
In [34]: n=int(input("Enter number:"))
sum=0
i=1
while i<=n:
sum=sum+i
i=i+1
print("The sum of first",n,"numbers is :",sum)
Enter number:10
The sum of first 10 numbers is : 55
Q3 write a program to prompt user to enter password until
entering correct password Python@1234.
In [35]: password=""
while password!="Python@1234":
password=input("Enter password:")
print("Thanks for confirmation")
Enter password:upendra
Enter password:rohit
Enter password:jayesh
Enter password:Python@1234
Thanks for confirmation
Infinite Loops
Some times a loop can execute infinite number of times without stopping also.
Example
i = 1
while True: # The body of this while loop keep on execuing because condition is always true
......print('Hello', i) # This program never going to terminates
......i=i+1
In [ ]:
Nested Loops
Sometimes we can take a loop inside another loop,which are also known as nested loops.
In [2]: for i in range(3):
print("Upendra")
for j in range(2):
print('Jayesh')
Upendra
Jayesh
Jayesh
Upendra
Jayesh
Jayesh
Upendra
Jayesh
Jayesh
In [4]: for i in range(4):
for j in range(4):
#print("i=",i," j=",j)
print(f"i = {i} j = {j}")
i = 0 j = 0
i = 0 j = 1
i = 0 j = 2
i = 0 j = 3
i = 1 j = 0
i = 1 j = 1
i = 1 j = 2
i = 1 j = 3
i = 2 j = 0
i = 2 j = 1
i = 2 j = 2
i = 2 j = 3
i = 3 j = 0
i = 3 j = 1
i = 3 j = 2
i = 3 j = 3
Write a program to dispaly *'s in Right angled triangled
form.
In [40]: n = int(input("Enter number of rows:"))
for i in range(1,n+1):
for j in range(1,i+1):
print("*",end=" ")
print()
Enter number of rows:10
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
Alternative way:
In [42]: n = int(input("Enter number of rows:"))
for i in range(1,n+1):
print("* " * i)
Enter number of rows:4
*
* *
* * *
* * * *
Q. Write a program to display *'s in pyramid style (also
known as equivalent triangle)
In [43]: n = int(input("Enter number of rows:"))
for i in range(1,n+1):
print(" " * (n-i),end="") # Equivalent Triangle form
print("* "*i)
Enter number of rows:10
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
Transfer Statements
1. break:
We can use break statement inside loops to break loop execution based on some condition
1. continue:
We can use continue statement to skip current iteration and continue next iteration
In [44]: for i in range(10):
if i==7:
print("processing is enough..plz break")
break
print(i)
0
1
2
3
4
5
6
processing is enough..plz break
In [45]: cart=[10,20,600,60,70]
for item in cart:
if item>500:
print("To place this order insurence must be required")
break
print(item)
10
20
To place this order insurence must be required
In [47]: # lets see above code with continue
cart=[10,20,600,60,70]
for item in cart:
if item>500:
print("To place this order insurence must be required")
continue
print(item)
10
20
To place this order insurence must be required
60
70
In [49]: cart=[10,20,500,700,50,60]
for item in cart:
if item >= 500:
print("We cannot process this item :",item)
continue
print(item)
10
20
We cannot process this item : 500
We cannot process this item : 700
50
60
To print odd numbers in the range 0 to 9
In [48]: for i in range(10):
if i%2==0:
continue
print(i)
1
3
5
7
9
In [50]: numbers=[10,20,0,5,0,30]
for n in numbers:
if n==0:
print("Hey how we can divide with zero..just skipping")
continue
print("100/{} = {}".format(n,100/n))
100/10 = 10.0
100/20 = 5.0
Hey how we can divide with zero..just skipping
100/5 = 20.0
Hey how we can divide with zero..just skipping
100/30 = 3.3333333333333335
Questions:
Q 1. What is the difference between for loop and while loop in Python?
We can use loops to repeat code execution
Repeat code for every item in sequence ==>for loop
Repeat code as long as condition is true ==>while loop ### Q 2. How to exit from the loop?
by using break statement ### Q 3. How to skip some iterations inside loop?
by using continue statement.
pass statement:
pass is a keyword in Python.
In our programming syntactically if block is required which won't do anything then we can define that
empty block with pass keyword. ### use case of pass:
Sometimes in the parent class we have to declare a function with empty body and child class
responsible to provide proper implementation. Such type of empty body we can define by using pass
keyword. (It is something like abstract method in java).
In [51]: for i in range(100):
if i%9==0:
print(i)
else:
pass
0
9
18
27
36
45
54
63
72
81
90
99
In [56]: math.log(100,5)
2.8613531161467867
Out[56]:
Lets Make a game: Guessing Game
In [13]: import random # imported to generate Random Numbers
lower = int(input("Enter Lower bound:- ")) # Taking Inputs
upper = int(input("Enter Upper bound:- ")) # Taking Inputs
x = random.randint(lower, upper) # to generate random number
while True:
guess = int(input("Guess a number:- ")) # taking guessing number as input
if x == guess: # Condition testing
print("Congratulations!! You guessed correctly ")
print("You must be really smart ")
break # once guessed correctly it will break the
elif x > guess:
print("You guessed too small!")
elif x < guess:
print("You Guessed too high!")
Enter Lower bound:- 1
Enter Upper bound:- 50
Guess a number:- 20
You Guessed too high!
Guess a number:- 10
You guessed too small!
Guess a number:- 15
You guessed too small!
Guess a number:- 17
You Guessed too high!
Guess a number:- 16
Congratulations!! You guessed correctly
You must be really smart
Same Guessing game with little improvement. Now tell user
the number of attempts they have and if not done in those
number of try, then tell them "better luck next time"
In [14]: import random # imported to generate Random Num
import math # to perform mathematical calula
lower = int(input("Enter Lower bound:- ")) # Taking Inputs
upper = int(input("Enter Upper bound:- ")) # Taking Inputs
x = random.randint(lower, upper) # to generate random number
Number_of_Try=round(math.log(upper - lower + 1, 2)) # Formula to calculate number of
print(f"Hey You will get {Number_of_Try} attempts to guess the number")
count=0 # initiliaze number of guesses i
while count<=Number_of_Try:
count=count+1 # increase the count by 1
guess = int(input("Guess a number:- ")) # taking guessing number as inpu
if x == guess: # Condition testing
print("Congratulations!! You guessed correctly ")
print("You must be really smart ")
break # once guessed correctly it will
elif x > guess:
print("You guessed too small!")
elif x < guess:
print("You Guessed too high!")
if count>Number_of_Try:
print(f" the number is {x} ")
print(" Better luck Next time! ")
Enter Lower bound:- 1
Enter Upper bound:- 50
Hey You will get 6 attempts to guess the number
Guess a number:- 25
You Guessed too high!
Guess a number:- 15
You guessed too small!
Guess a number:- 20
You Guessed too high!
Guess a number:- 17
You guessed too small!
Guess a number:- 18
Congratulations!! You guessed correctly
You must be really smart
In [ ]:
Assignment 2:
1. For all these questions, Please use loops and avoide using
ready made function/methods as much as possible.
2. Follow Assignment submission template shared in google
classroom.
1. Write a Python Program to find the GCD (greatest common divider) of two numbers entered by the
user.
2. write a Python Program to find the factorial of a number entered by the user.
3. Write a python program that prints the following pyramid on the screen. The number of the lines must
be obtained from the user as input.
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
4. Write a program to find those numbers which are divisible by 7 and multiple of 5, between 1500 and
2000 (both included).
5. Write a python program to construct the following pattern, using a nested for loop.
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
6. Write a code mimicking KBC (Kaun Banega Karodpati). Let user enter his/her details (name, age, etc.)
and ask minimum 5 questions. Tell user the amount he/she has won and inform that the amount will be
deposited in given bank account.
7. Frame Your own question and solve using tools/techniques learned in this unit.
In [ ]: