Conditionals (if/elif/else)
Conditionals in Python
Section titled “Conditionals in Python”Introduction
Section titled “Introduction”Conditionals allow your program to make decisions and execute different code paths based on conditions.
Syntax
Section titled “Syntax”if condition: # code to execute if condition is Trueelif another_condition: # code to execute if another_condition is Trueelse: # code to execute if all conditions are FalseBasic Examples
Section titled “Basic Examples”age = 18
if age >= 18: print("You can vote")else: print("Too young to vote")Multiple Conditions
Section titled “Multiple Conditions”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"Grade: {grade}") # Grade: BTruthiness and Falsiness
Section titled “Truthiness and Falsiness”# Falsy values: False, None, 0, 0.0, "", [], {}, set()# Everything else is truthy
if []: # ❌ — empty list is falsy print("Never runs")
if [1, 2]: # ✅ — non-empty list is truthy print("Always runs")
if "": # ❌ — empty string is falsy print("Never runs")Ternary Expression
Section titled “Ternary Expression”# Syntax: value_if_true if condition else value_if_falseage = 20status = "Adult" if age >= 18 else "Minor"print(status) # Adult
# With functionsresult = "even" if x % 2 == 0 else "odd"Nested Conditionals
Section titled “Nested Conditionals”user = {"role": "admin", "active": True}
if user["active"]: if user["role"] == "admin": print("Full access granted") elif user["role"] == "editor": print("Edit access granted") else: print("Read-only access")else: print("Account deactivated")Short-Circuit Evaluation
Section titled “Short-Circuit Evaluation”# and — stops at first Falsedef expensive(): print("Expensive function called!") return True
if False and expensive(): # expensive() is NEVER called print("Won't print")
# or — stops at first Trueif True or expensive(): # expensive() is NEVER called print("Short-circuited!")Common Mistakes
Section titled “Common Mistakes”# ❌ Wrong: Assignment instead of comparisonif x = 10: # SyntaxError!
# ✅ Correctif x == 10: pass
# ❌ Wrong: Comparing boolean with ==if is_valid == True: # Redundant!
# ✅ Correctif is_valid: passBest Practices
Section titled “Best Practices”- Avoid nesting deeper than 3 levels — flatten with early returns
- Use
elifinstead of nestedifwhen conditions are mutually exclusive - Prefer positive conditions —
if active:overif not inactive: - Use
infor multiple comparisons —if x in (1, 2, 3):instead ofif x == 1 or x == 2 or x == 3: - Keep conditions simple — extract complex logic into named variables
Practice Exercises
Section titled “Practice Exercises”Exercise 1: Write a program that checks if a number is positive, negative, or zero.
Exercise 2: Create a simple calculator that takes two numbers and an operator (+, -, *, /) and performs the operation.
Exercise 3: Build a login system that checks username and password from a dictionary.