5. if, elif, else Syntax
Below are syntax examples of an if block, an if-else block, and an if-elif-else block.
1if condition1:2 # < code to run if condition1 is true >34if condition1:5 # < code to run if condition1 is true >6else:7 # < code to run if condition1 is false >89if condition1:10 # < code to run if condition1 is true >11elif condition2:12 # < code to run if condition1 is false AND condition2 is true >13else:14 # < code to run if condition1 is false AND condition2 is false >
The if and elif conditions are logical expressions. Examples: var>1, var==1, var != 1.
Syntax rules: each if, elif, else line ends with a colon. Code bocks are indented with 4 spaces.
NOTE: in an if statement followed by 1 or more elif statements, after the first true condition, the other subsequent conditions are not checked. For example, the following code will print ‘Hello’ and not ‘World’ even though both conditions are true.
1var = 1002if var != 1:3 print('Hello')4elif var > 1:5 print('World')
1>>>Hello