The if ... elif ... else Statements
Sometimes, the programmer has to test multiple conditions and execute statements depending on those conditions. if ... elif ... else statement is useful in such situations. Consider the following syntax of if ... elif ... else statement:
if condition1: statement1 elif condition2: statement2 else: statement3
Flowchart of Python if..elif.. else Statement
We can also write a group of statements after colon. The group of statements in Python is called a suite .
While writing a group of statements, we should write them all with proper indentation .
Indentation represents the spaces left before the statements . The default indentation used in Python is 4 spaces.
Let's write a program to display a group of messages using if statement.
print('a') print('b') if y==2:
These statements are inside 'if x==1' statement. Hence if the condition is True (i.e. x==1 is satisfied), then the above 3 statements are executed. Thus, the third statement 'if y==2' is executed only if x==1 is True.
At the next level, we can find the following statements:
These two statements are typed with 8 spaces before them and hence they belong to the same group (or suite). Since they are inside 'if y==2' statement, they are executed only if condition y==2 is True.