Learning LibraryCore Coding LibraryKids

Comparisons: asking yes-or-no questions

Code makes decisions by asking yes-or-no questions. Is the health low? Are the points enough? Every question gets one of two answers: True or False.

The big idea

A comparison like health <= 0 asks a question, and Python answers it with True or False.

See it in code

1Start simple

Code makes decisions by asking yes-or-no questions. > means greater than, and Python answers each question with True or False:

python
print(10 > 3)
print(10 < 3)
Run it — each question gets one of two answers:
True
False

10 > 3 is True, and 10 < 3 is False. Every comparison lands on one of those two answers.

2A step further

You can ask questions about a variable, too. == (two equals signs) checks whether two values are exactly equal:

python
health = 100
print(health == 100)
print(health == 50)
Run it — True when they match, False when they don't:
True
False

health really is 100, so health == 100 is True; it isn't 50, so that one is False. Note the two equals signs — that's how you ask, not store.

3In our world

Now our hero, down to 0 health. We ask two questions: <= means less than or equal to, and == we just met. Python answers each True or False:

python
health = 0

print("Is the hero defeated?")
print(health <= 0)

print("Full health?")
print(health == 100)
Run it — each question gets a True or a False:
Is the hero defeated?
True
Full health?
False

0 <= 0 is True (0 really is less-than-or-equal-to 0), and 0 == 100 is False. These True/False answers are exactly what an if needs to make a choice.

The same idea, everywhere

Comparisons power every decision in code. Is the enemy past the bottom? Is today's price above its average? Did the player type the right word? Each is a comparison handing back True or False for an if to act on.

Try it yourself

Add a question: is health less than 50? Write print(health < 50). Then change health to 100 at the top and see which answers flip.

The common mistake

Using one = when you mean two. A single = stores a value (health = 100), while == asks whether two things are equal (health == 100). Mixing them up is one of the most common beginner bugs of all.

What it unlocks

Yes/no answers feed straight into conditionals, and you can join several questions together with boolean logic.

Older, or want more depth? Read the Teens version →