
🐍 Lesson 16: Python If...Else (Checking Conditions)
1. What is If...Else?
In short → If...Else statements check whether a condition is true or false, and run code accordingly.
More formally → If...Else statements allow you to execute code based on whether a condition is True or False.
2. Syntax Structure
- if → checks the first condition
- elif → checks another condition
- else → runs if none of the conditions are true
3. Summary
✅ if → runs when the condition is true
✅ elif → for checking another condition
✅ else → runs when the condition is false
✅ You can also use nested if-else
python
# ===== 1. Simple If Statement =====
age = 18
if age >= 18:
print("You are an adult.")
# ===== 2. If...Else =====
print(f"\n===== If...Else =====")
temperature = 25
if temperature > 30:
print("It's a hot day!")
else:
print("It's a nice day.")
# ===== 3. If...Elif...Else =====
print(f"\n===== If...Elif...Else =====")
score = 75
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}")
# ===== 4. Nested If =====
print(f"\n===== Nested If =====")
num = 15
if num > 0:
print(f"{num} is positive")
if num % 2 == 0:
print("and even")
else:
print("and odd")
# ===== 5. Short Hand If =====
print(f"\n===== Short Hand =====")
a = 10
b = 20
# One line if
if a < b: print("a is less than b")
# Ternary operator
result = "Even" if a % 2 == 0 else "Odd"
print(f"{a} is {result}")You should see
You are an adult. ===== If...Else ===== It's a nice day. ===== If...Elif...Else ===== Score: 75, Grade: C ===== Nested If ===== 15 is positive and odd ===== Short Hand ===== a is less than b 10 is Even