Compare values, combine conditions with and/or/not, and branch your program with if, elif, and else.
Why: comparisons ask a true/false question about two values. They are the building blocks of every decision your program makes.
print(5 > 3) # True
print(5 == 5) # True (== asks "are these equal?")
print(5 != 3) # True (!= asks "are these different?")
print(5 >= 5) # True
print('a' < 'b')# True (strings compare alphabetically)Why: combine several conditions. "and" is True only when both sides are True; "or" is True when at least one side is; "not" flips True and False.
age = 25
has_ticket = True
print(age >= 18 and has_ticket) # True (both must hold)
print(age < 13 or age > 65) # False (neither holds)
print(not has_ticket) # FalseWhy: this is how a program chooses what to do. Python uses indentation (spaces) — not braces — to show which lines belong inside the if. The colon and the indent are required.
score = 82
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
else:
grade = 'C'
print(grade) # BNote: Python treats some values as "falsy" — they act like False in a condition. Empty things (0, "", [], {}, None) are falsy; almost everything else is truthy. This lets you check "is there anything here?" without comparing to empty.
name = ''
if name: # an empty string is falsy
print(f'Hi {name}')
else:
print('No name given') # this runs
items = [1, 2]
if items: # a non-empty list is truthy
print('Has items') # this runs