Complex Conditions
Complex conditions are an expansion of simple conditions, and allow for more functionality.
If a user is over a certain age, then they can drive a car legally. But what if they are not over a certain age?
Else and Elif statements help with this logic.
Key Points
Complex Conditions allow for more decision making around data.
Else statements make things happen when the initial condition was false.
Elif statements provide additional conditions before continuing.
Operators
To make conditions work properly you must have an understanding of the following operators.
Each operator changes how each conditional statement works.
| Example Code | Explanation |
|---|---|
| if age < 18: | Checks if age is less than 18 |
| if age > 18: | Checks if age is greater than 18 |
| if age <= 18: | Checks if age is less than or equal to 18 |
| if age >= 18: | Checks if age is greater than or equal to 18 |
| if age == 18: | Checks if age is exactly equal to 18 |
| if age != 18: | Checks if age is not equal to 18 |
Complex Condition: Else Example
Else statements allow for decision making when the initial condition is false.
The below example checks to see if a user’s age is greater than 50.
If it is, the output is “You are old!”.
If it is not, the output is “You are young!”.
if age > 50:
print("You are old!")
else:
print("You are young!")
Complex Condition: Elif Example
Elif statements allow for further conditional statements if the previous conditional statement was false.
The below example checks to see if the user’s age is greater than 50.
If it is, the output “You are old”.
If it is, an elif (Else if) statement is used to see if the user’s age is greater than 21.
If it is, the output is “You are an adult”.
If it is not, the output is “You are young.”
if age > 50:
print("You are old!")
elif age > 21:
print("You are an adult!")
else:
print("You are young!")