What is Control flow?
Control flow is the order in which a programs code executes based on values and logic.
Python programming language is regulated by three types of control structures:
- Sequential statements.
- Selection statement.
- Repetition statement.
Are set of statements where the execution process will happen in sequence manner.
It is not commonly used because if the logic has broken in any line, then the complete source code execution will break.
To avoid this problem, selection and repetition statements are used
Are also called decision control statements or branching statements.
Selection statements allows a program to execute instructions based on which condition is true.
- if Statement.
If statement executes a block of code based on a specified condition.
Here is the syntax;
if condition: if-block
The if statement checks the condition first, if the condition evaluates to True the statement is executed in the if-block. Otherwise, it ignores the statements.
age= input('Enter your age:') if int(age) >= 40: print("You are an adult")
Enter your age:46 You are an adult
It evaluates the condition and will execute the body of if if the test condition is True, and else body if the condition is false
if condition: if-block; else: else-block;
age = input('Enter your age:') if int(age) >= 40: print("You are an adult.") else: print("You are a child.")
Enter your age:30 You are a child.
Checks multiple conditions for true and execute a block of code as soon as one of the conditions evaluates to true.
If no condition evaluates to true, the if…elif…else statement executes the statement in the else branch.
The elif stands for else if.
if if-condition: if-block elif elif-condition1: elif-block1 elif elif-condition2: elif-block2 ... else: else-block
age = input('Enter your age:') your_age = int(age) if your_age >= 70: print("Your are old") elif your_age >= 40: print("Your young") else: print("null")
Enter your age:80 Your are old
Also called loops and are used to repeat the same code multiple times.
Python has two repetitive statements namely:
- for Loop
Used to iterate over a sequence that is either a list, set, tuple or dictionary.
for index in range(n): statement
From the above syntax; n is the number of times the loop will execute and index is the loop counter
# list numbers = [10,12,13,14,17] # variable to store the sum sum = 0 # iterate over the list for index in numbers: sum = sum+index print("The sum is", sum)
The sum is 66
for index in range(4): print(index)
0 1 2 3
Python while statement allows you to execute a block of code repeatedly until a given condition is satisfied.
while condition: body
An example to print 6 numbers from 0 to 5:
max = 6 counter = 0 while counter < max: print(counter) counter += 1
0 1 2 3 4 5