Conditional Statements – if, else, elif

► Overview

Conditional statements allow your program to make decisions. Based on conditions, your program can execute different code. This is fundamental to creating intelligent, responsive programs.

► Real-World Analogy

Think of conditional statements like a traffic light:
» If light is green → go
» Elif light is yellow → slow down
» Else (red) → stop
» Your action depends on the condition

► Key Concepts

✓ if statement: Executes code if condition is True
✓ elif: Checks another condition if previous was False
✓ else: Executes if all conditions are False
✓ Indentation: Code under if must be indented

■ Conditional Examples

/code

age = 18

if age >= 18:
print(“You can vote”)
else:
print(“Too young to vote”)

Multiple conditions

score = 85

if score >= 90:
print(“Grade: A”)
elif score >= 80:
print(“Grade: B”)
elif score >= 70:
print(“Grade: C”)
else:
print(“Grade: F”)

► Important Points

✓ Conditions must evaluate to True or False
✓ Only one block executes (first True condition)
✓ else is optional
✓ elif allows multiple condition checks

► Remember

✓ Indentation is crucial in Python
✓ Use comparison operators (==, !=, <, >, <=, >=)
✓ Can combine conditions with and, or, not
✓ Test all possible conditions

■ Practice Challenge

  1. Check if number is positive, negative, or zero
  2. Determine if year is leap year
  3. Create grade calculator with multiple conditions