Chapter 06 ยท Decisions
Making Decisions
A program that always does the same thing is a machine with one button. Decisions let your program choose different paths depending on the situation.
"If the light is green, go; otherwise, stop." We make these if/otherwise decisions
all day. Code does the same with if and else.
Asking a yes/no question
An if statement runs its block only when a condition is true. The condition uses
a comparison:
age = 20
if age >= 18:
print("You are an adult.")
Two things to notice: the line ends with a colon :, and the code inside is
indented (pushed in with spaces). That indentation is how Python knows what belongs
inside the if.
The comparison operators
| Symbol | Means |
|---|---|
== | equal to (note: two equals signs) |
!= | not equal to |
> / < | greater than / less than |
>= / <= | greater or equal / less or equal |
if / else โ two paths
password = input("Enter password: ")
if password == "open123":
print("Access granted.")
else:
print("Access denied.")
if / elif / else โ many paths
Use elif ("else if") to check several possibilities in order:
score = int(input("Your score: "))
if score >= 75:
print("Distinction")
elif score >= 50:
print("Pass")
else:
print("Try again")
Ask the user for a number and print whether it is positive, negative, or zero โ using
if, elif and else.
= puts a value into a variable. == asks "are these equal?" Using
= inside an if is a classic bug. And don't forget the colon and the indentation โ
Python insists on both.
Recap
if condition:runs a block only when the condition is true.- Compare with
== != > < >= <=. elifadds more paths;elsecatches everything remaining.- Indentation defines what's inside โ it's not just for looks in Python.