In this part of the Python Basics tutorial, we will learn about how to use Conditional statements in python. They are also known as decision-making statements.
Conditional statements are control statements. They are used to control the flow of a program. These statements execute a set of commands (or a block of code) only when the specified condition is satisfied.
Remember to take care of indentation when using conditional statements in python as indentation is used to identify different blocks of code.
The main types of confitional statements are listed below
- If statements
- If-else statements
- Elif statements
These may also be nested.
The If statement evaluates a Boolean expression and executes the block of code only when the Boolean expression returns TRUE.
Consider the code block below.
>>> x = 20 >>> if x<100: ... print("x is less than 100") ... x is less than 100 >>>
The If-else statement evaluates the Boolean expression specified.
It then executes the block of code present inside the if block, if the condition returns TRUE.
Otherwise, it executes a different block of code present in the else block (i.e. if the condition returns FALSE).
Example: Check if the number is odd or even.
>>> x = 3 >>> if x%2==0: ... print("even") ... else: ... print("odd") ... odd >>>
>>> x = 10 >>> if x%2==0: ... print("even") ... else: ... print("odd") ... even >>>
Elif statements are used to check multiple conditions only if the given if condition false.
It is similar to an if-else statement. The only difference here is that in else doesn’t check any condition but elif checks the condition specified.
Elif conditional statement is exclusive to python.
Have a look at the example given below.
>>> x = 0 >>> if x==0: ... print("x is zero") ... elif x>0: ... print("x is positive") ... else: ... print("x is negative") ... x is zero
>>> x = -100 >>> if x==0: ... print("x is zero") ... elif x>0: ... print("x is positive") ... else: ... print("x is negative") ... x is negative