Python 3 – IF…ELIF…ELSE Statements
In computer programming, conditional statements are key to creating decision-making capabilities in your code. Python 3’s IF…ELIF…ELSE statement is a fundamental building block of these capabilities, allowing you to test for certain conditions and execute different blocks of code based on those conditions.
Structure of an IF…ELIF…ELSE Statement
The basic structure of an IF…ELIF…ELSE statement in Python 3 is as follows:
if condition:
# if block
elif condition:
# elif block
else:
# else block
The IF block is executed if the initial condition is true. If the initial condition is false, the code moves on to the ELIF condition. If the ELIF condition is true, the ELIF block is executed. If both the initial IF and the ELIF conditions are false, the ELSE block is executed instead.
Let’s take a look at how this works in practice.
Example: Using IF…ELIF…ELSE Statements to Control Flow
Suppose you’re writing a program that needs to take in a user’s age and output a message based on that age. If the user is under 18, the program should tell them they’re too young to enter. If they’re between 18 and 65, the program should tell them they’re eligible to enter. If they’re over 65, the program should tell them they’re too old to enter.
Here’s how you could do that using an IF…ELIF…ELSE statement:
age = int(input("Enter your age: "))
if age < 18:
print("Sorry, you're too young to enter.")
elif age >= 18 and age <= 65:
print("Congratulations, you're eligible to enter!")
else:
print("Sorry, you're too old to enter.")
First, we take in the user’s age as an input and convert it to an integer using the int()
function. Then, we use an IF…ELIF…ELSE statement to test for the three different conditions based on the user’s age. The code only executes one of the three blocks depending on which condition is true.
Note the use of the and
keyword to test for a compound condition (i.e. the user’s age being between 18 and 65). This is a common technique in conditional statements.
Conclusion
In summary, the IF…ELIF…ELSE statement in Python 3 allows you to create decision-making capabilities in your code, testing for different conditions and executing different blocks of code based on those conditions. By mastering this fundamental coding structure, you can create more powerful and flexible programs that can respond intelligently to user input and external factors.