Learning LibraryCore Coding LibraryKids

if / else: let your code decide

Sometimes your code needs to choose. if checks whether something is true and runs one set of steps when it is — and else covers what to do when it is not.

The big idea

if runs a block of code only when a test is true; else runs a different block when it is false.

See it in code

1Start simple

Sometimes code needs to choose. if checks whether something is true, and runs the indented block only when it is:

python
health = 0
if health <= 0:
    print("Game over!")
Run it — the block runs because the test is true:
Game over!

health <= 0 was true, so the if block ran and printed the message. Had it been false, that line would simply be skipped.

2A step further

else covers what to do when the test is false. Our canvas is 500 wide, so x > 500 asks whether a star has slipped off the right edge:

python
x = 300
if x > 500:
    print("Off the edge!")
else:
    print("Still on the canvas.")
Run it — the false test sends us to the else branch:
Still on the canvas.

300 > 500 is false, so Python skipped the if and ran the else instead. Change x to 540 and the other branch would fire.

3In our world

Now the same check drives a real star. With x at 540, x > 500 is true — so we wrap it back around by subtracting 500 before drawing:

python
from art import Canvas, star

screen = Canvas.create()
Canvas.fill(screen)

x = 540
if x > 500:
    x = x - 500
    print("Off the edge - wrapped it back!")
else:
    print("Still on the canvas.")

star(screen, x, 250, size=90)
Run it — the star that would have vanished appears on the left instead:
Off the edge - wrapped it back!
A single yellow star near the left side of a dark navy canvas.

Because 540 > 500 was true, Python ran the if block: it changed x to 40 and printed the message. The else block was skipped completely.

The same idea, everywhere

Every choice a program makes is an if. If the player has 0 health, show Game Over. If a number is even, color it blue. If the answer is right, add a point. if/else is how code reacts to the world instead of doing the exact same thing every time.

Try it yourself

Change x to 300 and run again — now the test is false, so the else runs and the star stays put. Then add an elif x < 0: line to catch stars that drift off the left edge too.

The common mistake

Forgetting the colon or the indent. The : at the end of the if line and the spaces in front of the block are both required — they are how Python knows which steps belong to the choice.

What it unlocks

Decisions grow up fast: comparison operators write the tests, boolean logic combines them, and while loops keep going as long as a test stays true.

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