Python if-else Statements
Conditional statements let your program make decisions. Python uses if, elif (else if), and else keywords to control the flow of execution based on conditions.
The if Statement
The simplest form of conditional:
age = 20
if age >= 18:
print("You are an adult")
print("You can vote")Remember: The code block under if must be indented (4 spaces).
The if-else Statement
Execute one block if the condition is True, another if False:
temperature = 35
if temperature > 30:
print("It's hot outside! βοΈ")
else:
print("It's pleasant outside π€οΈ")The if-elif-else Statement
Check multiple conditions in sequence:
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Score: {score}, Grade: {grade}") # Score: 85, Grade: BOnly the first matching condition executes β the rest are skipped even if they would also be true.
Nested Conditions
You can nest if statements inside other if statements:
age = 25
has_license = True
has_insurance = True
if age >= 18:
if has_license:
if has_insurance:
print("You can drive!")
else:
print("You need insurance")
else:
print("You need a license")
else:
print("You are too young to drive")Tip: Avoid deep nesting. Use logical operators to flatten conditions:
# Better approach with logical operators
if age >= 18 and has_license and has_insurance:
print("You can drive!")
elif age < 18:
print("You are too young to drive")
elif not has_license:
print("You need a license")
else:
print("You need insurance")Ternary Operator (Conditional Expression)
A one-line if-else:
# Syntax: value_if_true if condition else value_if_false
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult
# With function calls
x = -5
result = abs(x) if x < 0 else x
print(result) # 5
# Nested ternary (use sparingly!)
score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
print(grade) # BBest Practice: Use ternary operators only for simple conditions. Complex logic should use regular if-elif-else.
Truthy and Falsy Values in Conditions
Python evaluates any value as True or False in a condition:
# Falsy values: 0, 0.0, "", [], {}, (), set(), None, False
# Everything else is Truthy
name = ""
if name:
print(f"Hello, {name}")
else:
print("Name is empty") # This executes
items = [1, 2, 3]
if items:
print(f"List has {len(items)} items") # This executes
else:
print("List is empty")
# Common pattern: check before accessing
data = None
if data:
process(data)
else:
print("No data available")Conditions with in and is
# Membership testing with 'in'
fruit = "apple"
if fruit in ["apple", "banana", "cherry"]:
print(f"{fruit} is in the list")
# Identity testing with 'is'
result = None
if result is None:
print("No result yet")
if result is not None:
print(f"Result: {result}")Multiple Conditions with Logical Operators
# AND: both conditions must be True
age = 25
income = 55000
if age >= 21 and income >= 50000:
print("Loan approved")
# OR: at least one condition must be True
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
# NOT: reverses the condition
is_banned = False
if not is_banned:
print("Access granted")
# Complex conditions (use parentheses for clarity)
has_premium = True
age = 25
country = "US"
if (has_premium or age >= 21) and country == "US":
print("Full access granted")Pattern Matching (match-case, Python 3.10+)
Python 3.10 introduced structural pattern matching, similar to switch in other languages:
status_code = 404
match status_code:
case 200:
print("OK")
case 301:
print("Moved Permanently")
case 404:
print("Not Found")
case 500:
print("Internal Server Error")
case _:
print(f"Unknown status: {status_code}")Pattern Matching with Guards
def classify_number(n):
match n:
case 0:
return "zero"
case n if n > 0:
return "positive"
case n if n < 0:
return "negative"
print(classify_number(5)) # positive
print(classify_number(-3)) # negative
print(classify_number(0)) # zeroPattern Matching with Structures
def handle_command(command):
match command.split():
case ["quit"]:
print("Quitting...")
case ["hello", name]:
print(f"Hello, {name}!")
case ["add", *numbers]:
total = sum(int(n) for n in numbers)
print(f"Sum: {total}")
case _:
print("Unknown command")
handle_command("hello Alice") # Hello, Alice!
handle_command("add 1 2 3 4") # Sum: 10
handle_command("quit") # Quitting...Practical Example: Simple Calculator
"""
A simple calculator using if-elif-else.
"""
def calculator():
print("Simple Calculator")
print("-" * 20)
num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
if num2 == 0:
print("Error: Division by zero!")
return
result = num1 / num2
else:
print(f"Unknown operator: {operator}")
return
print(f"{num1} {operator} {num2} = {result}")
calculator()Summary
ifexecutes code when a condition isTrueelifchecks additional conditions after a failedifelseruns when all previous conditions areFalse- Use ternary operator for simple one-line conditionals
- Python values are truthy or falsy β
0,"",[],Noneare falsy - Use
infor membership testing,isfor identity testing - Use
and,or,notto combine conditions match-case(Python 3.10+) provides structural pattern matching
Next, we'll learn about Python for loops.