So far, your programs have run from top to bottom without stopping or choosing paths. Real software needs to react to different situations: a login check, a weather alert, or a game move. Python gives you this power with the
if statement.The if statement
age = 18
if age >= 18:
print("You can vote.")
print("Program ends.")Look closely at that structure. The
if line ends with a colon (:). This tells Python: "I am about to define a block of code." The lines underneath are indented (usually four spaces). That indentation is not for looks; it defines which commands belong to the decision.If
age >= 18 is True, Python runs the print inside. If it is False, Python skips that indented block and continues with whatever comes after at the same level as if. This skipping behavior is key: code outside the indent always runs.else: the alternative path
number = 7
if number % 2 == 0:
print("Even")
else:
print("Odd")else handles the case where the if condition was False. It must follow an if. You cannot use else on its own. In this example, we check if a number is even using the modulo operator %, which gives you the remainder of division.elif: multiple options
temp = 5
if temp > 25:
print("Hot")
elif temp < 10:
print("Cold")
else:
print("Mild")elif stands for "else if." It lets you check multiple options in a single chain. Python reads them top to bottom and stops as soon as it finds one that is True. else catches everything else.Nesting: decisions inside decisions
is_adult = True
has_license = False
if is_adult:
if has_license:
print("Can drive")
else:
print("No license yet")
else:
print("Too young to check license")Nesting means putting one
if block inside another. You use this when a second condition only matters if the first was true. Here, we check for a license only because the person is already an adult.