Conditional Statements (If-Elif-Else)
Give your code a brain. Learn how to make decisions and control the flow of your program based on dynamic conditions.
Making Decisions
Programs need to react differently depending on the situation. If a user is logged in, show their profile; if not, show the login page. We handle this logic using if, elif (else-if), and else statements.
The Syntax
The code block under an if statement only runs if the condition evaluates to True.
temperature = 25
if temperature > 30:
print("It's a hot day, stay hydrated!")
elif temperature > 20:
print("It's a beautiful day for a walk.")
else:
print("It's getting cold, wear a jacket.")Remember: The indentation dictates what code belongs to which condition!
Logical Operators: Combining Conditions
What if you have multiple rules? You can chain them using and, or, and not.
- and: BOTH sides must be True.
- or: AT LEAST ONE side must be True.
- not: Flips True to False, and vice-versa.
has_ticket = True
is_vip = False
if has_ticket and not is_vip:
print("Please wait in the standard line.")