The if…elif statement
The if…elif statement in Python is used when you need to choose between more than two alternatives. The elif clause can be used to create a number of conditions that can be evaluated. The syntax of the statement is:
if condition: statements elif condition: statements elif condition: statements . . . else: statements
Consider the following example:
print('Available cars: ') print('1.BMW') print('2.Ford') print('3.Tesla') print('4.Chrysler') print('5.Toyota') x = int(input('Select your car: ')) if x == 1: print('You have selected BMW.') elif x == 2: print('You have selected Ford.') elif x == 3: print('You have selected Tesla.') elif x == 4: print('You have selected Chrysler.') elif x == 5: print('You have selected Toyota.') else: print ('Invalid selection.')
Here is the output:
Available cars: 1.BMW 2.Ford 3.Tesla 4.Chrysler 5.Toyota Select your car: 2 You have selected Ford.
The example above begins by displaying a menu. A user is prompted to make a selection by entering a number between 1 and 5. The user’s selection is then evaluated. If the user enters anything other then these numbers, the Invalid selection message will be displayed.