Learning Objectives
-
if statement
-
if-else statement
-
if-elif-else statement
Tutorial on Conditional Statements
If Statement
-
Syntax (how to write If statement in Python?)- statement(s)
1 2
if test expression/condition: do this
-
Here, the program evaluates the test expression and will execute statement(s) only if the test expression/condition is True.
-
If the test expression is False, the statement(s) is not executed.
-
In Python, the body of the if statement is indicated by the indentation. The body starts with an indentation, and the first unindented line marks the end.
-
Python interprets non-zero values as True (even negative values).
-
None and 0 are interpreted as False.
-
Empty strings, empty lists, empty dicts, empty tuples, and empty sets are also interpreted as False.
Flowchart:
Example: Python program to detect if a number is even. (% sign tells us the remainder of an expression. Any number with a remainder of 0 after dividing by 2 must be even.)
If-else Statement
- Syntax:
1 2 3 4
if test expression: Body of if else: Body of else
- The if-else statement evaluates test expression and will execute the body of if only when the test condition is True.
- If the condition is False, the body of else is executed. Indentation is used to separate the blocks.
Flowchart:
Example:
The test expression is False as 5 is not an even number. So the body of if statement is not executed. The body of else is executed.
if-elif-else Statement
- Syntax:
1 2 3 4 5 6
if test expression: Body of if elif test expression: Body of elif else: Body of else
-
The elif is short for else if. It allows us to check for multiple expressions.
- If the condition for if is False, it checks the condition of the next elif block and so on.
-
If all the conditions are False, the body of else is executed.
-
Only one block among the several if-elif-else blocks is executed according to the condition.
-
The if block can have only one else block. But it can have multiple elif blocks.
Flowchart:
Example:
5 is neither divisible by 2 nor by 3. So the if and elif statements are False. The else block will be executed here.
Now, let’s try to understand the given example.
- We first assigned the value 5 to z.
- The control shifts to the next line where z%2 is checked. 5 is not divisible by 2, so the control doesn’t shift to the body of if.
- Then, the elif statement: z%3 is executed. Since 5 is not divisible by 3, the body of elif is not executed.
- Finally, the else statement is executed. The control shifts to the body of else, and “z is neither divisible by 2 nor by 3” is printed.
- Point to be noted: The conditions are checked in a top to bottom order. If any of the above if or elif condition is True, it’ll be executed, and no further conditions will be checked.
- Can you figure out what z=6 will print in the given example?