The Elif statement in Python is an extension of the if statement where additional conditions are specified. If the if-statement condition is not met (false), the code passes to the elif statement condition. If these conditions are met (true), then the operations specified in the elif statement are performed.
The Elif statement helps to solve problems when you have several different operations to be performed. Depending on which condition is met, a specific operation should be performed, but not all at the same time. To achieve this there is the else-if statement which is a combination of the if and else statement. The image below shows a flow chart that can be described as an “Elif ladder”. What the flow chart shows is that:
The Elif statement is an extension of the if statement where additional conditions are specified
Important to note:
The Elif statement has similar syntax as the if statement. First, the reserved words elif are specified and followed by a logical expression. Within the brackets, you specify the operations to be performed if the conditions of the elif statement are met (true). Note that the if statement has higher priority than the elif statement. This means that when the conditions for the if statement are true, then the elif and the else statement will be ignored.
Note that an elif statement can only be created in conjunction with an if statement and must be followed by an else statement.
if (logical expression): statement executing elif (logical expression): what this statement supposed to do else (logical expression): what this statement supposed to do
A store has the following discount system:
We now want to program a program that prints how much discount the customer should receive. We will now try to program the system using if-, else- and elif statements.
cost = 400; # The cost for the purchase is set to 400 if(cost >= 2000): print("The discount is 20%") elif(cost >= 1500): print("The discount is 15%") elif(cost >= 1000): print("The discount is 10%") elif(cost >= 500): print("The discount is 5%") else: print("No discount");
The printout in this case becomes
Since all conditions in the above if and else-if statements are false