2.2 Conditional Branches
Conditional branches let a program choose different code paths for different situations. Python uses if, elif, and else for branching.
if
An if statement checks a condition. If the condition is True, Python runs the indented block under it. If the condition is False, Python skips that block.
age = int(input("Enter your age: "))
if 0 < age < 18:
print("Minor")One possible run:
Enter your age: 17
MinorIn Python, indentation is not decoration. It is part of the syntax. Statements that belong to the same if block must use the same indentation level.
if-else
if-else is used for a two-way choice: run the if block when the condition is true; otherwise run the else block.
Here is a leap-year example. A year is a leap year if it satisfies one of these conditions:
- It is divisible by 4, and not divisible by 100.
- Or it is divisible by 400.
year = int(input("Enter a year: "))
is_leap_year = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
if is_leap_year:
print("Leap year")
else:
print("Common year")One possible run:
Enter a year: 2020
Leap yearSaving the complex condition into is_leap_year makes the if line easier to read. In real programs, this is often more maintainable than placing a long condition directly inside if.
if-elif-else
When there are more than two cases, use if-elif-else. Python checks conditions from top to bottom. It runs the first branch whose condition is True, then skips the remaining branches.
c = input("Enter a character: ")
if 'a' <= c <= 'z':
print("Lowercase")
elif 'A' <= c <= 'Z':
print("Uppercase")
elif '0' <= c <= '9':
print("Digit")
else:
print("Special character")One possible run:
Enter a character: T
UppercaseThe order of elif branches matters. Put more specific or higher-priority conditions earlier, and use else as the fallback case.