This chapter introduces conditional logic and control flow.
Conditional logic is based on comparing values using boolean comparators:
Python has three logical operators:
if condition:
# Code to execute if condition is True
if condition:
# Code if condition is True
else:
# Code if condition is False
if condition1:
# Code if condition1 is True
elif condition2:
# Code if condition2 is True
else:
# Code if neither condition is True
A factor of a positive integer n is any positive integer less than or equal to n that divides n with no remainder.
def factors(n):
for i in range(1, n + 1):
if n % i == 0:
print(i)
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
Use conditional expressions for simple if-else situations in single line:
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult
# Equivalent to:
if age >= 18:
status = "adult"
else:
status = "minor"
Conditional statements can be nested inside each other:
age = 25
income = 45000
if age >= 18:
if income > 50000:
tax_rate = 0.25
print("High income taxpayer")
elif income > 30000:
tax_rate = 0.20
print("Middle income taxpayer")
else:
tax_rate = 0.10
print("Low income taxpayer")
else:
print("Too young to file taxes")
tax_rate = 0.0
Parentheses help clarify complex conditions:
score = 85
attendance = 95
# Without parentheses - and has higher precedence than or
if score > 80 and attendance > 90 or score > 90:
print("Excellent student")
# With parentheses for clarity
if (score > 80 and attendance > 90) or score > 90:
print("Excellent student")
# Use print statements to check conditions
x = 5
y = 10
print(f"x = {x}, y = {y}")
print(f"x > 3: {x > 3}")
print(f"y < 15: {y < 15}")
print(f"x > 3 and y < 15: {x > 3 and y < 15}")
if x > 3 and y < 15:
print("Condition is true")
else:
print("Condition is false")
# Test boundary values
for age in [17, 18, 19, 65, 66]:
if age >= 18 and age <= 65:
print(f"Age {age}: Working age")
elif age < 18:
print(f"Age {age}: Minor")
else:
print(f"Age {age}: Retirement age")
This chapter introduces conditional logic and control flow, including comparisons, logical operators, if/elif/else statements, loops, break/continue, exception handling, and advanced conditional patterns.
Mastering these concepts allows you to write programs that make decisions and handle different scenarios appropriately.