Comparing values: ask a yes-or-no question
Before a program can decide anything, it has to ask a question. Is the oven hot enough? Are the cookies gone? A comparison asks, and Python answers True or False.
The big idea
A comparison checks two values against each other and gives back a yes-or-no value, called a boolean: True or False.
See it in code
>= means "greater than or equal to." Print a check and you can see the answer Python gets:
oven_temp = 300
ready_temp = 350
print(oven_temp >= ready_temp)False
300 isn't greater than or equal to 350, so the answer is False. Change oven_temp to 350 and the same line prints True.
Two equals signs, ==, ask whether two things are the same. You can store the answer in a variable and give it a name that reads like a question:
cookies_left = 0
is_sold_out = cookies_left == 0
print("Sold out?", is_sold_out)
special = "brownies"
print(special == "cookies")Sold out? True False
== works on words as well as numbers. The words must match exactly, letter for letter, or the answer is False.
The real job of a check is to steer the program. Here > compares what the customer wants with what's in the case:
cookies_left = 5
how_many = int(input("How many? "))
if how_many > cookies_left:
print(f"Sorry, we only have {cookies_left}.")
else:
print("Coming right up!")How many? 8 Sorry, we only have 5.
how_many > cookies_left was True, so the first message ran. That's all an if needs: a check that answers yes or no.
Checks like these run constantly. A painting asks whether a row number is even. A game asks whether a ball has passed the wall, sixty times every second.
Try it yourself
Run the last program again and type 5 instead of 8. Which message do you get? Then change > to >= and type 5 once more. Why did the answer flip?
The common mistake
Using one equals sign when you mean two. = stores a value. == asks whether two values match. Writing if cookies_left = 0: stops the program, because Python expected a question there.
What it unlocks
Comparisons are the questions behind every if and else. Join two of them with and, or, not and your program can make careful choices.