Nearby lessons
37 of 159Python - Flow Control
- Define flow control and its role in program execution
- Identify the three types of flow control statements
- Distinguish if, if-else, if-elif and if-elif-else conditional statements
- Write programs that find the biggest and smallest of three numbers
- Convert a digit to its word form using an if-elif-else ladder
Introduction
Flow Control decides the order in which Python statements are executed during program execution.
It helps the program make decisions, repeat tasks, and control the execution flow.
Types of Flow Control
| Category | Statements |
|---|---|
| Conditional Statements | if, if-elif, if-elif-else |
| Transfer Statements | break, continue, pass |
| Iterative Statements | for, while |
Conditional Statements
Conditional statements execute different blocks of code based on a condition.
Python provides the following conditional statements:
ifif-elifif-elif-else
1. if Statement
The if statement executes a block of code only when the condition is True.
Syntax:
if condition:
statement
Or
if condition:
statement1
statement2
statement3
Important Note
- If the condition is
True, all statements inside theifblock are executed. - If the condition is
False, the complete block is skipped.
Example 1 - if Statement
Example 2 - Favourite Brand
if with Multiple Statements
An if block can contain multiple statements.
Example - Multiple Statements
2. if-else Statement
The if-else statement is used when there are two possible actions.
- If the condition is
True, theifblock is executed. - If the condition is
False, theelseblock is executed.
Syntax:
if condition:
Action1
else:
Action2
Example 1 - if-else
Example 2 - Biggest of Two Numbers
3. if-elif Statement
When multiple conditions need to be checked, use the if-elif statement.
Python checks conditions from top to bottom.
Once a condition becomes True, the corresponding block is executed and the remaining conditions are skipped.
Syntax
Example - if-elif
Important Note
Only one matching block is executed. After that, all remaining conditions are skipped.
4. if-elif-else Statement
The else block executes when none of the above conditions are True.
Syntax
Example - if-elif-else
Program - Biggest of Three Numbers
Program - Smallest of Three Numbers
Program - Even or Odd Number
Program - Check Number Between 1 and 100
Program - Print Digit in Words
- Flow control decides the order in which Python statements are executed
- Conditional statements execute different blocks based on a condition
- Only one matching block runs and the remaining conditions are skipped
- The else block executes when none of the conditions are True
- Python provides if, if-elif and if-elif-else conditional statements