Learning LibraryCore Coding LibraryKids

and, or, not: combine yes-or-no answers

Sometimes one yes-or-no answer is not enough. and, or, and not let you join answers together — so your code can check two things at once.

The big idea

and, or, and not combine True/False values into a single True or False.

See it in code

1Start simple

Sometimes one yes-or-no answer isn't enough. and joins two answers, and is True only when both of them are:

python
print(True and True)
print(True and False)
Run it — and needs both sides to be True:
True
False

True and True is True, but True and False is False — one False is enough to sink an and.

2A step further

or is the easygoing one: it's True when either side is true. Here the hero has no sword, but does have a shield:

python
has_sword = False
has_shield = True
print(has_sword or has_shield)
Run it — or only needs one side to be True:
True

Even though has_sword was False, or still gave True because has_shield was true. Just one side needs to hold.

3In our world

Our hero should move only when a key is down and the hero is still on-screen — a job for and. The new tool here is not, which flips an answer to its opposite:

python
key_down = True
on_screen = True

can_move = key_down and on_screen
print("Can the hero move?")
print(can_move)

off_screen = not on_screen
print("Is the hero off-screen?")
print(off_screen)
Run it — the answers get combined:
Can the hero move?
True
Is the hero off-screen?
False

Both key_down and on_screen were True, so and gave True. And not True is False, so the hero is not off-screen. Two answers, one clear decision.

The same idea, everywhere

Real decisions often need more than one test. Open the door if you have the key and it's unlocked. Win if you reach the flag or you beat the timer. Combine tests, and your code can handle the tricky cases.

Try it yourself

Change key_down to False and run again — now and gives False, because both parts must be True. Then try or instead of and and see how the answer changes.

The common mistake

Thinking and is loose like everyday talk. In code, and is strict: both sides must be True, or the whole thing is False. If you only need one side to be True, use or.

What it unlocks

Combined answers plug straight into conditionals, and each answer usually starts as a comparison.

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