Python If...Else & Conditional Expressions
Conditional statements allow your Python programs to make decisions and execute different blocks of code depending on whether certain conditions are true or false.
1. The Basic if Statement
The if statement evaluates a boolean expression. If the expression evaluates to True, the indented block of code runs. If False, Python skips the block.
age = 18
if age >= 18:
print("You are eligible to vote!")
2. The if...elif...else Chain
When you have multiple conditions to check sequentially, use elif (short for "else if") and else to catch everything else. Python evaluates conditions from top to bottom and stops at the first True branch.
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Your grade is: {grade}")
3. Nested if Statements
You can place if statements inside other if statements when you need to check a secondary condition only after a primary condition is met.
is_logged_in = True
is_admin = False
if is_logged_in:
if is_admin:
print("Welcome to the Admin Dashboard.")
else:
print("Welcome to your user profile.")
else:
print("Please log in to continue.")
4. Conditional Expressions (Ternary Operator)
Python supports a concise one-line shorthand for if...else statements, often called the ternary operator. It is useful for simple variable assignments based on a condition:
# Syntax: [on_true] if [condition] else [on_false]
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status) # Output: Adult
5. Truthy and Falsy Values in Conditions
In Python, conditions don't strictly require comparison operators like == True. Any object can be evaluated in a boolean context.
- Falsy values (evaluate to
False):False,None, numeric zero (0,0.0), empty sequences/collections ("",[],(),{}), and custom objects where__bool__or__len__returns0. - Truthy values (evaluate to
True): Everything else.
username = "Alice"
# Pythonic way to check if a string is non-empty
if username:
print(f"Hello, {username}!")