The if elif else construct in Python allows the nesting of multiple if statements, i.e. if then otherwise statements.
In fact in the Python language to implement the multiple selection, this construct is used (for those who know other languages it is equivalent to the switch-case).
Syntax if elif else in Python
First of all, we note that the word elif is the abbreviation for else if, that is, otherwise if.
First example elif Python
So let’s create a first example of using the if elif else construct.
Create a program, which reads in input a vote represented by a character between A and E and then prints its meaning.
Let’s consider for example that:
A corresponds to excellent;
B corresponds to distinct;
C corresponds to discrete;
D corresponds to sufficient;
E it corresponds to insufficient.
First of all I take the vote as input and then I compare it with one of the letters to print the corresponding vote in output. If the letter does not match any of the default, an error message will be displayed.
So here is a possible solution that uses the if elif else construct in Python:
grade = input('Enter grade A, B, C, D or E:') if vote == 'A': print('The grade', grade, 'matches very good') elif vote == 'B': print('The vote', vote, 'matches distinct') elif vote == 'C': print('The grade', grade, 'matches fair') elif vote == 'D': print('The grade', grade, 'matches sufficient') elif vote == 'E': print('The grade', grade, 'matches insufficient') else: print('the letter entered does not correspond to any grade')
Second example elif Python
Let’s take another example to better understand the use of the construct.
On a railway line, compared to the full rate, pensioners benefit from a 10% discount, students 15% and finally the unemployed 25%.
Then, by coding pensioners with a P, students with an S and the unemployed with a D, write a program that, once the cost of a ticket and any condition of the user is requested, displays the amount to be paid.
First of all, we take the price and status as input, that is, if the user is unemployed, retired or a student.
Then just check the status and calculate the ticket price accordingly.
So here’s a possible resolution using the if elif else construct in Python:
price = float(input('Enter the ticket price:')) state = input('Enter the state knowing that D = Unemployed, P = retired, S = students:') if state == 'D': price = price * 75/100 elif state == 'P': price = price * 90/100 elif state == 'S': price = price * 85/100 else: price = price print('You belong to category', status, 'so you will pay:', price)
If you are already familiar with price = price * 75/100, write price * = 0.75 and so on.