In which order, statements are going to execute, is decided by flow control.
Types of flow control statement:
Conditional statements/Selection Statements (if, if-else, if-elif-else)
Iterative Statements (loops for and while)
Transfer Statements (break, continue, pass)
Now I am going to discuss these 3 types of flow control statements in detail.
Conditional Statements/Selection Statements:
Among multiple available options select one and execute it, such type of statements are considered as Conditional or Selection statements. Various Conditional statements are:
in the above example if the name equals to ‘mujtaba’ then the corresponding If condition is executed.
Note 1: We can take any number of elif conditions after if condition.
Note 2: else is always optional.
Possible combinations of if:
If elif else
Some programs on conditional statements:
#Program to find biggest of given 2 numbers from the keyboard
#Program to find biggest of given 3 numbers from the keyboard
Note: In this example we are using eval function so that number can be any type int or float.
#Write a program to check whether the given number is even or odd
Iterative Statements (loops for and while):
Some times we require a group of statement execute iteratively until the given condition is true.
for loop: also known as for-each loop
For each_element in sequence:
do some action
Sequence can be string, list, range tuple or set.
Example: Enter a string from keyboard and count number of characters in string.
Example: Print numbers from 0 to 10
while (in python there is no do while loop)
Example: Print numbers from 10 to 1 in descending order.
Example: Print sum of numbers of list.
Note: for loop is mostly recommended in python. If we don't know the number of Iteration in advance then while loop is used.
While Loop syntax:
Example: Print numbers from 1 to 10 using while loop.
Example: Sum of first n numbers
When to use ‘for loop’ and ‘while loop’?
If the number of iterations are known in advance, ‘for loop’ will be used otherwise 'while loop' will be used.
loop inside a loop is known as Nested loops.
Ex: print the below pattern.
* * *
* * * *
* * * * *
Example: Print the below pattern.
3 3 3
4 4 4 4
break: ‘break’ is used to break loop execution based on some condition.
continue: We can use continue within loop to skip the current iteration and go to the next iteration
Example: Print all odd numbers up to 10 by using continue.
pass: pass is a keyword in python. In our programming syntactically if block is required, which won’t do anything, then we can use pass. It is an empty/null statement like other languages.