FLOW CONTROL
The flow control statements alter the execution flow of the program based on certain conditions while running the program. The control flow statements of Python can be classified as follows.
1. Selection statements
2. Looping statements
3. Jumping statements
SELECTION STATEMENTS
Selection statements are useful for the selection of one set of statements from many sets of statements for execution while the program is running. The following statements of Python are referred to as selection statements.
1. if statement
2. if-else statement
3. elif statement
4. match-case statement
The Python language has a boolean type with True and False as values. Also, it treats any non-zero value result as True and a zero result as False in control flow conditional tests
if statement
The if statement syntax is as follows.
if condition:
statement_1
...
statement_n
If the condition evaluation results in True, the statements 1 to n are executed; otherwise, not. For example
name = 'John'
if name=='John'
print("Welcome John")
In this case, the test condition results in True, the if block print statement gets executed to print the welcome message.
if-else statement
The syntax of the if-else statement is as follows.
if condition:
statement_1
...
statement_n
else:
statement_a
....
statment_x
If the condition evaluation results in True, the if block statements from 1 to n are executed; otherwise, the else block statements from a to x are executed. For example,
a = 100
b = 200
if a==b:
print(" a and b are equal")
else:
print("a and b are not equal")
In this case, the condition evaluation (a==b) results in False, and hence the else block statement is executed to print the message "a and b are not equal".
elif (else if) statement
The elif statement is useful to select one group of statements from many groups of statements. The syntax of the elif statement is as follows.
if condition1:
statements
elif condition2:
statements
elif condition3:
statements
else:
statements
The conditions are tested sequentially from the beginning (condition1) to the end (condition3) until any one of the conditions results in True. The block of statements that corresponds to the condition which evaluated to True is executed, and the program control moves out of the elif statement. If none of the condition results in True, then the else block (default) statements are executed. The else block in the elif statement is optional. For example,
a = 100
b = 200
if a==b:
print("a and b are equal")
elif a>b:
print("a is greater than b")
else:
print("a is less than b")
The condition (a==b) is false, and the next condition (a>b) is also false, and hence the default else block of statement is executed to print "a is less than b". If
a = 300
b = 300
the first condition is True and hence executes the corresponding block of statements to print "a and b are equal". The elif statement terminates after that without testing any other condition.
match-case statement
The match-case statement is similar to the switch statement in C/C++/Java, but the control flow is different in Python. The syntax of this statement is as follows.
match value:
case v1:
print("value is matching with cas v1")
case v2:
print("value is matching with case v2")
case v3:
print("value is matching with case v3")
case _:
print("value is not matching any case value")
The keywords used in this control structure are match and case. The control flow is as follows. The value is compared with the first case value (v1); if it matches, it executes the statements belonging to the case and then terminates the match-case. Otherwise, comparison continues with the next case (v2) and so on. If the value does not match any of the case values, it executes the (default) case that is represented by an underscore (wild card). The default case (_) is optional and always appears at the end of the match-case statement.
Let us consider an example.
value = True
match value:
case 10:
print("It is an integer")
case True:
print("It is a boolean")
case "string":
print("It is a string")
case _:
print("It is default", value)
The value does not match the first case, but with the second case. The statement belongs to the case
print("It is a boolean")
is executed and then terminates the statement.
LOOP STATEMENTS
Python has two statements for iterative control of program execution. They are for loop and while loop. The for loop is used when the number of iterations is fixed at the time of writing code, whereas the while loop is preferred if the number of iterations is not known.
for loop
The syntax of the for loop is as follows.
for var in [list_of_values]:
statements
The for loop statements are executed for each value in the list_of_values. A value from the list is assigned sequentially to the variable var for each iteration.
Let us learn the for loop with some examples.
for i in [1,3,5]:
print(i, end=' ')
This for loop statement prints: 1 3 5
The loop iterates three times, with a value of i equal to 1, 3, and 5 during the first, second, and third iterations respectively. The loop prints the value of i in each iteration.
for i in ['one', 'John', 'location']:
print(i)
The list has strings as values for i. The values for i are the strings 'one', 'John', and 'location' during the first, second, and third iterations, respectively. The output of the loop is as follows.
one
John
location
The list need not have the values of the same type as shown below. It has integer, string and boolean type values.
for i in [1,'Ram', True]:
print(i, end=',')
The loop prints the following.
1,3,5
for loop with range function: The range function in Python has three arguments: start, stop and step. The default values for start and step arguments are 0 and 1 respectively. It returns the list of values depending on these three arguments. The function signature is as follows.
range (start=0, stop, step=1)
For example,
for i in range(5):
print(i, end=',')
The arguments of the above range function are start=0, step=1 and stop=5. It returns the list [0 1 2 3 4]. The range is only up to the stop value, but not including the stop value. Hence, the for loop iterates five times with i values of 0,1,2,3,4. Let us consider another example to understand the range function.
for i in range(2,6):
print(i, end=',')
The arguments of the above range function are start=2, stop=6 and step=1(default). The function returns the list [2,3,4,5]. The loop iterates 4 times with values 2,3,4 and 5 for i. An example with all three arguments is as follows.
for i in range (3, 15, 2):
print(i, end=',')
The range function with the arguments start=3, stop=15 and step = 2 returns the list [3,5,7,9,11,13]. The for loop iterates over the values in the list and prints the following.
3,5,7,9,11,13
for loop with else: The for loop has an optional else part, which will be executed always after completing all iterations. The syntax is as follows.
for var in list_of_values:
statements
else:
statements
For example,
for i in range(5):
print(i, end=',')
else:
print(i)
This for loop prints the following: 0,1,2,3,4,4
while loop
The syntax of the while loop is as follows.
while loop_condition:
statements
The while loop iterates as long as the loop_condition is True. It gets terminated once the loop condition becomes False. The loop condition is evaluated for every iteration before executing its block of statements. Any non-zero numeric value or a boolean True value is True for the while loop. The numeric zero or a boolean False is False. Some examples with results are as follows.
while True:
print(True, end='.')
This while loop iterates infinite number of times and during each iteration, it prints True on the screen as follows.
True.True.True........
Use Ctrl-C to terminate the code.
while False:
print(False)
This while loop never executes the print statement (never enters the while block).
while -0.01: # any non-zero numeric value is True
print("always true")
while 0.0: # numeric zero is False; never enters the while block
print("always false)
There is no do-while loop in Python. The do-while loop guarantees at least one iteration. The same can be achieved using a while loop using loop_condition and its block statements. One instance to achieve the same is as follows.
x = True
while x: # guarentees first iteration
block statments can change x to stop the iterations
while loop with else: The else part of the while loop is optional and when used always executed after completing all iterations. For example,
x = 5
while x<10:
x = x+1
else:
print("end of while loop")
The while loop iterates and at the end prints the message: end of while loop.
Jumping (branching) statements
In Python, there are two branching or jumping statements for loops: the break statement and the continue statement. The syntax is as follows.
break # just use the keyword
continue # just use the keyword
break statement: The break statement breaks the loop (the innermost loop if nested) and exits the for/while loop as soon as it is executed. The following examples illustrate the break statement.
for i in range(5):
print(i, end=',')
if i==3:
break
This prints 0,1,2,3 on the screen; the if statement condition is True when the i value is 3, which executes the break statement and terminates the for loop.
for i in ['one', 'two', 'three']:
print(i)
for j in range(1,3)
print(i)
if i==1:
break
The output is as follows.
one
1
two
1
three
1
The outer for loop iterates three times to print the strings 'one', 'two', and 'three'. The inner for loop has to iterate two times for every iteration of the outer for loop, but it iterates only once because of the break statement. Observe that the break statement breaks only the inner for loop.
continue statement: The continue statement in the for/while loop suspends the remaining statements of the current iteration when executed inside the loop. It starts the next iteration after checking the loop condition. Let us learn the continue statement with a while loop. The following while loop is written to print from 1 to 10, but can print only odd numbers because of the continue statement.
i=0
while i<11:
i = i+1
if i%2 == 0:
continue
print(i, end=',')
The output of the program is: 1,3,5,7,9
The if statement condition is True if the value of i is even, which in turn executes the continue statement. The continue statement skips the remaining statements of the current iteration. Then it immediately moves the program control to the top of the while loop to check the while condition.
Nesting of control flow statements
Any control flow statement can be nested with any other control flow statement. The following code snippets show some examples.
if condition: # the for loop is nested under the if statement
for i in range(5):
print(i)
for i in range(5): # for loop block has a while statement nested and while has an if block nested
while i<3:
if condition:
break
print(i)
Programs
Let us write a program to generate the Fibonacci numbers sequence of length n. A Fibonacci number is the sum of the previous two numbers in the series. The first two Fibonacci numbers are 0 and 1.
f1=0 # first fib number
f2=1 # second fib number
n = input("enter the length of the Fib sequence = ") # ask the user to enter the length of the seq
n = int(n) # read n type is string, convert it to int
next = 0
print(f1,f2,end=',') # print first two numbers of fib sequence
for i in range(n-2): # first two numbers are defined; generate remaining
next = f1 + f2 # next fib number is the sum of the previous two numbers
print(next, end=',') # new fib number added to the sequence
f1=f2 # redefine the previous two numbers to generate the next number
f2=next
The program is self-explanatory for the reader with knowledge of the for loop and library functions (range, input, int). The comments on the line help you to understand the program.
Let us write another program to illustrate control flow statements. This time to use selection statements (if-else statement). The person is senior if he crosses 60 years. Let us find whether a person is senior or not based on his birth year.
# program to find whether a person is senior or not
current_year = int(input("Enter the current year ")) # program input
name = input("Enter the name of the person ")
birth_year = int(input("Enter the birth year of the person "))
age = current_year - birth_year # program logic
if age>=60:
print("The person is senior ", age) # program output tied with logic
else:
print("The person is not senior ", age) # program output tied with logic
The output of the program is as follows.
Enter the current year 2025
Enter the name of the person John
Enter the birth year of the person 1985
The person is not senior 40
Run again to feed different input and observe the input
Enter the current year 2025
Enter the name of the person Peter
Enter the birth year of the person 1965
The person is senior 60