Combining Multiple Conditions with elif
In addition to using elif to check a single condition, you can also combine multiple conditions within a single elif statement. This allows you to create more complex decision-making logic in your Python programs.
The syntax for combining multiple conditions with elif is as follows:
if condition1:
## code to be executed if condition1 is True
elif condition2 and condition3:
## code to be executed if condition1 is False and both condition2 and condition3 are True
elif condition4 or condition5:
## code to be executed if condition1 is False and either condition4 or condition5 is True
else:
## code to be executed if all the above conditions are False
In this example, the second elif statement checks if both condition2 and condition3 are True, while the third elif statement checks if either condition4 or condition5 is True.
Here's an example of combining multiple conditions with elif to determine the season based on the month:
month = 7
if month in [12, 1, 2]:
print("It's Winter!")
elif month in [3, 4, 5]:
print("It's Spring!")
elif month in [6, 7, 8]:
print("It's Summer!")
elif month in [9, 10, 11]:
print("It's Autumn!")
else:
print("Invalid month!")
In this example, the program checks the value of the month variable against multiple conditions using elif. If the month is in the range of 12, 1, or 2, the program prints "It's Winter!". If the month is in the range of 3, 4, or 5, the program prints "It's Spring!", and so on.
By combining multiple conditions with elif, you can create more complex and versatile decision-making logic in your Python programs, allowing you to handle a wider range of scenarios and requirements.