|Syntax:||if condition1 :
|Description:||Executes statements1 if condition1 is true,
Else it executes statements2 if condition2 is true,
Else it executes statements3.
The elif is optional, and can be used zero or multiple times.
The else is optional, only one else is allowed.
|Parameters:||condition1,2||A value or an expression evaluates to a 0 or not 0|
|Related:||if, while, for, condition|
The if .. elif .. else statement is an extended version of the if statement. It allows multiple conditions to be tested and different blocks of statements to be run depending on which condition is true.
The if condition is tested first, if it is true the statements that follow it are executed and the remaining elif and else statements are skipped. If the first if condition is not true then the next elif condition is tested, and if true then the statements after that elif are executed. Further elif conditions may be present and they will be tested only if the previous if and elif conditions were not true. Finally if all the conditions were not true then the statements following the final else will be executed. Note only the statements following the first true condition will be executed, all other statements will be skipped.
The elif line is optional, there may be no elif lines, or there can be one or more elif lines.
The else line is optional, if present only one else line is allowed.
The condition can be a value or an expression. An expression may contain contain comparison operators. Such as == , < , >= etc.
If the condition evaluates to true (or a non zero value) then the following block of code is run. (a block of code is where all the lines are indented by the same number of space characters)
Example using if .. else:
a = 30 if a < 20: print('a is less than 20, a is ', a) else: print('a is greater than 20, a is ', a)
Example using if .. elif .. else
a=-23 if a > 1000: print('a is a really big number, a is', a) elif a > 500: print('a is a big number, a is', a) elif a > 100: print('a is a medium number, a is', a) elif a >= 0: print('a is a small number, a is', a) else: print('a must be a negative number, a is', a)