8. Flow control - 25 min read
- Why should we learn about flow control?
- Flow control
- Sequential flow
- Conditional flow
- Looping flow
- Sequential statements
- Conditional or Decision-making statements
- if statement
- if else statement
- if elif else statement
- Looping
- while loop
- for loop
- Infinite loops
- Nested loops
- Loops with else block (or) else suit
- Where loops with else block flow is helpful?
- break statement
- continue statement
- pass statement
- return statement
- Programs
8.
Flow control
Why should we learn about flow control?
- Simple answer: To understand the flow of statements execution in a program.
- In any programming language, statements will be executed mainly in three ways,
- Sequential.
- Conditional.
- Looping.
Flow control
- The order of statements execution is called a flow of control.
- Based on requirement the program's statements can execute in different ways like sequentially, conditionally and repeatedly etc.
1. Sequential
- Statements execute from top to bottom, means one by one sequentially.
- By using sequential statements, we can develop only simple programs.
2. Conditional
- Based on the conditions, statements used to execute.
- Conditional statements are useful to develop better and complex programs.
- Based on the conditions, statements used to execute randomly and repeatedly.
- Looping execution is useful to develop better and complex programs.
1. Sequential statements
- Sequential statements execute from top to bottom, means one by one sequentially.
Program sequential execution
Name demo1.py
print(“one”)
print(“two”)
print(“three”)
Output
one
two
three
|
2. Conditional or Decision-making statements
- if
- if
else
- if
elif else
- else suite
3. Looping
- while loop
- for loop
4. others
- break
- continue
- return
- yield (we will discuss in function chapter)
- pass
2. Conditional or Decision-making statements
2.1 if statement
syntax
if condition:
if block statements
out of if block statements
|
- if statement contains an expression/condition.
- As per the syntax colon (:) is mandatory otherwise it throws syntax error.
- Condition gives the
result as a bool type, means either True or False.
- If the condition result is True, then if block statements will be executed
- If the condition result is False, then if block statements won’t execute.
Program Executing if block statements by using if statement
Name demo2.py
num = 1
print(“num==1 value is: ”, (num==1))
if num
== 1:
print(“if block
statements executed”)
Output
num==1 value is: True
if block statements executed
|
Program: executing out of if block statements
Name demo3.py
num = 1
print(“num==2 value is: ”,
(num==2))
if num
== 2:
print(“if block
statements”)
print(“out of if block
statements”)
Output
num==2 value is: False
out of if block statements
|
When should we use if statement?
- If you want to do either one thing or nothing at all, then you should go for if statement.
2.1 if else statement
syntax
if condition:
if block statements1
else:
else block
statements2
|
- if statement contains an expression/condition.
- As per the syntax colon (:) is mandatory otherwise it throws syntax error
- Condition gives the result as bool type, means either True or False
- If the condition result is True, then if block statements will be executed
- If the condition result is False, then else block statements will be executed.
Program Executing if block statements by using if else statement
Name demo4.py
num =1
print(“num==1 value is: ”,
(num==1))
if num
== 1:
print(“if block
statements executed”)
else:
print(“else block
statements executed”)
Output
num==1 value is: True
if block statements executed
|
Program printing else block statements
Name demo5.py
num =1
print(“num==2 value is: ”,
(num==2))
if num
== 2:
print(“if block
statements executed”)
else:
print(“else block
statements executed”)
Output
else block statements
executed
|
Program User name validation checking by using if else statement
Name demo6.py
user_name =”nireekshan”
name = input(“Please enter
user name: ”)
if user_name== name:
print(“Welcome to Gmail
: ”, name)
else:
print(“Invalid user
name, please try again”)
Output
Please enter user name: nireekshan
Welcome to Gmail: nireekshan
Please enter user name:
chiru
Invalid user name,
please try again
|
Program User name validation checking by using if else statement
Name demo7.py
user_name =”nireekshan”
user_password =
“dvs”
name = input(“Please enter
user name: ”)
password = input(“Please
enter your password: ”)
if (user_name == name) and
(user_password == password):
print(“Welcome to Gmail: ”, name)
else:
print(“Invalid user
name or password, please try again”)
Output
Please enter your name: nireekshan
Please enter your password: dvs
Welcome to Gmail: nireekshan
Please enter your name: nireekshan
Please enter your password: sampurneshbabu
Invalid user name or password, please try
again
|
Make a note
When should we use if else statement?
- if and else blocks are BEST friends,
- So, we should not break the relationship between if and else by writing other statements in between.
- Conclusion of the story
- In between, if and else blocks we should not write any other statements
Program In
between if and else we should not write anything
Name demo7a.py
x=1
if x==1:
print("if
block")
print("Hello ")
else:
print("else
block")
Output
SyntaxError: invalid syntax
|
- If you want to do either one thing or another thing, then you should go for if else statement.
2.2 if elif else statement
syntax
if condition1
if block statements
elif condition2
elif
block1 statements
elif condition3
elif
block2 statements
else
else
block statements
|
- if statement contains an expression/condition.
- As per the syntax colon (:) is mandatory otherwise it throws an error
- Condition gives the result as bool type means either True or False
- If the condition result is True, then any matched if or elif block statements will execute.
- If all if and elif conditions results are False, then else block statements will execute.
Make a note
- Here, else part is an optional
Program printing corresponding value by using if, elif, else
statements
Name demo8.py
print(“Please enter the
values from 0 to 4”)
x=int(input(“Enter a number:
“))
if x==0:
print(“You entered:”,
x)
elif
x==1:
print(“You
entered:”, x)
elif
x==2:
print(“You
entered:”, x)
elif
x==3:
print(“You
entered:”, x)
elif
x==4:
print(“You
entered:”, x)
else:
print(“Beyond the
range than specified”)
output
Enter a number: 1
You entered: 1
Enter a number: 100
Beyond the range
|
When should we use if elif
else statement
- If we want to choose one option from many options, then we should use if elif else statements.
Programs by using conditional statements
Program Find
biggest of given 2 numbers from the command prompt
Name demo9.py
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
if x>y :
print("Biggest
Number is: ", x)
else :
print("Biggest
Number is: ", y)
Output
Enter First Number: 10
Enter Second Number: 20
Biggest Number is: 20
|
Program Find
biggest of given 3 numbers from the command prompt
Name demo10.py
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
z=int(input("Enter Third Number: "))
if (x>y) and (x>z):
print("Biggest
Number is: ",x)
elif y>z :
print("Biggest
Number is: ",y)
else :
print("Biggest
Number is: ",z)
Output
Enter First Number: 10
Enter Second Number: 20
Enter Second Number: 30
Biggest Number is: 30
|
Program To
find the number belongs to which group
Name demo11.py
x=int(input("Enter number:"))
if (x>=1) and (x<=100) :
print("Entered
number", x ,"is in between 1 to 100")
else :
print("Entered
number", x ,"is not in between 1 to 100")
Output
Enter number: 55
Entered number 55 is
in between 1 to 100
Enter number:
201
Entered number 201 is
not in between 1 to 100
|
3. Looping
- If we want to execute a group of statements in multiple times, then we should go for looping kind of execution.
- while loop
- for loop
3.2 while loop
- If we want to execute a group of statements repeatedly until the condition reaches to False, then we should go for while loop.
Syntax
while condition:
statements
|
- while loop contains an expression/condition.
- As per the syntax colon (:) is mandatory otherwise it throws a syntax error
- Condition gives the result as bool type means either True or False
- If the condition result is True, then while loop executes till the condition reaches to False.
- If the condition result is False, then while loop execution terminates.
while loop main parts
- Initialization section.
- Condition section.
- Either increment or decrement by using arithmetic operator.
while loop explanation
Initialization section.
- Initialization is the first part in while loop.
- Here, before entering the condition section, initialization part is required.
Condition section
- With the initialized value, the next step is checking the condition.
- In python, while loop will check the condition at the beginning of the loop.
- In the first iteration:
- In the first iteration, if the condition returns True, then it will execute the statements which having inside while loop.
- In the first iteration, if the condition returns False, then
while loop terminates immediately.
Increment or decrement
- Next step is, increment or decrement section.
- In python, we need to use arithmetic operator inside while loop to increment or decrements the value.
- So, based on the requirement, the value will be either increment or decrement.
- In the second iteration:
- In the second iteration, if the condition returns True, then it will execute the statements which having inside while loop.
- In the second iteration, if the condition returns False, then while loop terminates immediately.
Conclusion
- Till condition is True the while loop statements will be executed.
- If the condition reaches to False, then while the loop terminates the execution.
Program Printing numbers from 1 to 5 by using while loop
Name demo12.py
x=1
while
x<=5:
print(x)
x+=1
print(“End”)
output
1
2
3
4
5
End
|
Program Printing even numbers from 10 to 20 by using while loop
Name demo13.py
x=10
while
(x>=10) and (x<=20):
print(x)
x+=2
print(“End”)
output
10
12
14
16
18
20
End
|
for loop
- Basically, for loop is used to get or iterate elements one by one from sequence like string, list, tuple, etc…
- While iterating elements from the sequence we can perform operations on every element.
Syntax
for variable
in sequence:
statements
|
Program printing elements from the list object
Name demo14.py
l1 = [10, 20, 30,
‘Nireekshan’]
for x
in l1:
print(x)
output
10
20
30
Nireekshan
|
Program printing characters from a string
Name demo15.py
x= ”python”
for ch
in x:
print(ch)
output
p
y
t
h
o
n
|
Program printing every item cost by adding gst from list
Name demo16.py
items_costs = [10, 20, 30,]
gst = 2
for x in items_costs:
print(x+gst)
output
12
22
32
|
Program printing elements by using range() function and for
loop
Name demo17.py
for x
in range(1, 5):
print(x)
output
1
2
3
4
|
Program sum of the items cost in list using for loop
Name demo18.py
item_costs = [10, 20, 30]
sum=0
for x in item_costs:
sum=sum
+ x
print(sum)
output
60
|
Infinite loops
- The loop which never ends is called infinite group.
Program infinite
loop
Name demo19.py
while True:
print(“Hello”)
output
Hello
Hello
Hello
.
.
.
|
Make a note
- To come out of the infinite loop we need to press ctrl + c
Nested loops
- It is possible to write one loop inside another loop, this is called nested loop
Program printing stars by using nested for loop
Name demo20.py
rows =
range(1, 5)
for x in rows:
for star in range(1, x+1):
print('* ', end=' ')
print()
output
*
* *
* * *
* * * *
|
Loops with else block (or) else suit
for with else
|
while with else
|
for variable in sequence:
statements
else:
statements
|
while
condition:
statements
else:
statements
|
- The statements are written after ‘else’ are called as else suite.
- The else suite will be always executed irrespective of the loop executed or not.
Program for with else
Name demo21.py
values = range(5)
for x in values:
print(“item
is available”)
else:
print(“sorry
boss, item is not available”)
output
item is available
item is available
item is available
item is available
item is available
sorry boss, item is not
available
|
Program for with else
Name demo22.py
values = range(0)
for x in values:
print(“item
is available”)
else:
print(“sorry
boss, item is not available”)
output
sorry boss, item is not available
|
Make a note
- Seems to be for loop and else suit both got executed.
Where this kind of execution will helpful?
- If you are searching an element from list object, if unable to find element then for loop won’t return anything, so at that time else suit help us to tell not found the element.
Program Element searching in list
Name demo23.py
group = [1, 2, 3, 4]
search = int(input(“Enter the element
in search: “))
for element in group:
if search == element:
print(“An element
found in group”, element)
break
else:
print(“Element not found”)
output
Enter element to
search: 4
An element found in group
: 4
Enter element to
search: 6
Element not found in
group
|
break statement
- The break statement can be used inside the loops to break the execution based on some condition.
- Generally, break statement is used to terminate the for loop and while loop.
- break statement we can use inside loops only otherwise it gives SyntaxError.
Program while loop without a break
Name demo24.py
x=1
while x<=10:
print(‘x=
’, x)
x+=1
print(“out
of the loop”)
output
x= 1
x= 2
x= 3
x= 4
x= 5
x= 6
x= 7
x= 8
x= 9
x= 10
out of the loop
|
Program printing just 1 to 5 by using while
loop and break
Name demo25.py
x=1
while x<=10:
print('x', x)
x+=1
if x == 5:
break
print("out of the
loop")
output
x= 1
x= 2
x= 3
x= 4
out of the loop
|
continue statement
- We can use continue statement to skip the current iteration and continue next iteration.
Program Applying discount based on condition
and printing remaining
Name demo26.py
cart=[10, 20, 500, 700,
50, 60]
for item in cart:
if item>=500:
continue
print("No discount applicable:
", item)
output
No discount
applicable: 10
No discount
applicable: 20
No discount
applicable: 50
No discount
applicable: 60
|
pass statement
- We can use pass statement when we need a statement syntactically, but we do not want to do any operation.
Program pass statement
Name demo27.py
num = [10, 20, 30,400,
500, 600]
for i in num:
if i<100:
print(“pass statement
executed”)
pass
else:
print("Give festival
coupon for these guys who bought: ",i)
output
pass statement
executed
pass statement
executed
pass statement
executed
Give festival coupon
for these guys who bought: 400
Give festival coupon
for these guys who bought: 500
Give festival coupon
for these guys who bought: 600
|
return statement
- Based on the requirement a function or method can return the result.
- If any function or the method is returning a value, then we need to write a return statement along with the value.
Program Function displaying information
Name demo28.py
def display():
print(“This
is python programming”)
display()
output
This
is python programming
|
Program Function displaying information and
that function returns None
Name demo29.py
def
display():
print(“This
is python programming”)
x
= display()
print(x)
output
This
is python programming
None
|
Make a note
- If any function is not returning anything then by default that function returns None data type.
Make a note
- If any function or the method is returning a value, then we need to write a return statement along with the value.
Program Function returns a result
Name demo30.py
def sum(a, b):
return a+b
res=sum(10,
20)
print(res)
output
30
|