The if Statement

So far your programs have run the same way every time — every line executes, top to bottom, no matter what. But real programs need to make decisions. Should the ball bounce? Is the player’s score high enough to win? That’s where the if statement comes in.

In this lesson you’ll learn how to give your program a condition to check, and only run certain code when that condition is true.

Open In Jupyter K-12

A Ball That Falls Forever

Run the cell below. A ball drops from the sky — and keeps going… forever. There’s nothing telling it to stop or come back. Click Stop (■) when you’ve seen enough.

Hint: You can hold down the left mouse button to move around the scene. Use the scroll wheel to zoom in and out.

import scene3d

scene = scene3d.Scene()
scene.set_sky('#1a1a2e')
scene.set_ground(length=10, width=10)

ball = scene3d.Shapes.Sphere(diameter=1, segments=16)
ball.set_color('#e94560')
ball.set_position(0, 8, 0)
scene.add(ball)

y = 8.0

@scene.on_frame
def animate(dt):
  global y
  y -= 3 * dt
  ball.set_position(0, y, 0)

scene.run()

The Problem — and the Fix

The ball just keeps falling because we never told it what to do when it hits the ground. Every frame, the program subtracts from y — no questions asked.

We need a way to say: if the ball reaches the ground, reset it to the top.”

That’s exactly what an if statement does. It checks a condition, and only runs the indented code underneath when that condition is True.

if y < 0:
    y = 8.0

Let’s add it and see what happens.

import scene3d

scene = scene3d.Scene()
scene.set_sky('#1a1a2e')
scene.set_ground(length=10, width=10)

ball = scene3d.Shapes.Sphere(diameter=1, segments=16)
ball.set_color('#e94560')
ball.set_position(0, 8, 0)
scene.add(ball)

y = 8.0

@scene.on_frame
def animate(dt):
  global y
  y -= 3 * dt

  if y < 0:
    y = 8.0

  ball.set_position(0, y, 0)

scene.run()

How the if Statement Works

An if statement has three parts:

if y < 0:
    y = 8.0
Part What it is Example
if The keyword that starts the statement if
Condition A question Python checks — is this True or False? y < 0
Colon : Marks the end of the condition :
Indented body The code that runs only when the condition is True y = 8.0

Indentation matters!

Python uses indentation (spaces at the start of a line) to know which lines belong inside the if. Any line indented under the if only runs when the condition is True. As soon as you go back to the left margin, you’re outside the if again.

if y < 0:
    y = 8.0          # inside the if — only runs when y < 0
    print('reset!')  # also inside
ball.set_position(0, y, 0)  # outside — always runs

Controlling a Growing Sphere

Here’s another example. Each frame, the sphere grows a little bigger. When it gets too large, an if statement resets it back to a small size.

Notice how size keeps increasing — until the condition size > 3 becomes True, and the if steps in.

import scene3d

scene = scene3d.Scene()
scene.set_sky('#0f3460')
scene.set_ground(length=10, width=10)

sphere = scene3d.Shapes.Sphere(diameter=1, segments=16)
sphere.set_color('#f5a623')
sphere.set_position(0, 1.5, 0)
scene.add(sphere)

ctx = scene.get_context('2d')
size = 0.2

@scene.on_frame
def animate(dt):
  global size
  size += 0.5 * dt

  if size > 3:
    size = 0.2

  sphere.set_scale(size, size, size)

  ctx.clear()
  ctx.fill_style = '#ffffff'
  ctx.fill_text(f'Size: {size:.2f}', 10, 28)

scene.run()

{ “question_type”: “multiple_choice”, “question”: “What character must appear at the end of every if condition?”, “options”: [ { “key”: “a”, “text”: “A semicolon ;” }, { “key”: “b”, “text”: “A colon :” }, { “key”: “c”, “text”: “A period .” }, { “key”: “d”, “text”: “An equals sign =” } ], “answer”: “b”, “submitted_answer”: “” }

{ “question_type”: “true_false”, “question”: “The indented code inside an if statement always runs, even when the condition is False.”, “answer”: “False”, “submitted_answer”: “” }

{ “question_type”: “multiple_choice”, “question”: “In the growing-sphere example, what happens when size > 3 is True?”, “options”: [ { “key”: “a”, “text”: “The program crashes” }, { “key”: “b”, “text”: “The sphere stops moving” }, { “key”: “c”, “text”: “size resets to 0.2” }, { “key”: “d”, “text”: “size doubles” } ], “answer”: “c”, “submitted_answer”: “” }

Comparison Operators

The condition inside an if statement uses a comparison operator to compare two values. Python gives you six of them:

Operator Meaning Example Result
< less than 3 < 5 True
> greater than 7 > 2 True
<= less than or equal to 4 <= 4 True
>= greater than or equal to 6 >= 9 False
== equal to 5 == 5 True
!= not equal to 3 != 7 True

Watch out! A single = assigns a value (x = 5). A double == compares two values (x == 5). Easy to mix up!

The examples below show a few of these operators in action inside 3D scenes.

Using == to Match an Exact Value

The == operator checks if two values are exactly equal. In the scene below, a counter increments each second. When it hits exactly 3, the ball changes color — demonstrating a precise match.

Click Stop (■) after you’ve watched a couple of cycles.

import scene3d

scene = scene3d.Scene()
scene.set_sky('#1a1a2e')
scene.set_ground(length=10, width=10)

ball = scene3d.Shapes.Sphere(diameter=1.5, segments=16)
ball.set_color('#aaaaaa')
ball.set_position(0, 1.5, 0)
scene.add(ball)

ctx = scene.get_context('2d')

elapsed = 0.0
count = 0

@scene.on_frame
def animate(dt):
  global elapsed, count
  elapsed += dt

  if elapsed >= 1.0:
    elapsed = 0.0
    count += 1

  if count == 5:
    count = 0

  if count == 3:
    ball.set_color('#e94560')
  else:
    ball.set_color('#aaaaaa')

  ctx.clear()
  ctx.fill_style = '#ffffff'
  ctx.font = '24px sans-serif'
  ctx.fill_text(f'Count: {count}  (turns red when count == 3)', 10, 32)

scene.run()

Multiple if Statements

You can use as many if statements as you need — Python checks each one independently.

The scene below has three zones: left, center, and right. A ball drifts across the scene, and a separate if statement handles each zone, changing the ball’s color and bouncing it back when it hits a wall.

Notice how all three if statements are checked on every frame — they don’t interfere with each other.

import scene3d

scene = scene3d.Scene()
scene.set_sky('#0f3460')
scene.set_ground(length=12, width=12)

ball = scene3d.Shapes.Sphere(diameter=1, segments=16)
ball.set_color('#f5a623')
ball.set_position(0, 0.8, 0)
scene.add(ball)

ctx = scene.get_context('2d')

x = 0.0
speed = 3.0
zone = 'center'

@scene.on_frame
def animate(dt):
  global x, speed, zone

  x += speed * dt

  if x > 4:
    speed = -speed
    x = 4

  if x < -4:
    speed = -speed
    x = -4

  if x < -1.5:
    zone = 'left'
    ball.set_color('#4488ff')

  if x > 1.5:
    zone = 'right'
    ball.set_color('#44cc88')

  if x >= -1.5 and x <= 1.5:
    zone = 'center'
    ball.set_color('#f5a623')

  ball.set_position(x, 0.8, 0)

  ctx.clear()
  ctx.fill_style = '#ffffff'
  ctx.font = '22px sans-serif'
  ctx.fill_text(f'Zone: {zone}  |  x = {x:.1f}', 10, 30)

scene.run()

{ “question_type”: “multiple_choice”, “question”: “Which operator checks if two values are exactly equal?”, “options”: [ { “key”: “a”, “text”: “= (single equals)” }, { “key”: “b”, “text”: “== (double equals)” }, { “key”: “c”, “text”: “!= (not equals)” }, { “key”: “d”, “text”: “>= (greater or equal)” } ], “answer”: “b”, “submitted_answer”: “” }

{ “question_type”: “true_false”, “question”: “When you have three if statements in a row, Python checks all three independently on every frame.”, “answer”: “True”, “submitted_answer”: “” }

{ “question_type”: “multiple_choice”, “question”: “What does the != operator do?”, “options”: [ { “key”: “a”, “text”: “Checks if two values are equal” }, { “key”: “b”, “text”: “Assigns a value to a variable” }, { “key”: “c”, “text”: “Checks if two values are NOT equal” }, { “key”: “d”, “text”: “Checks if a value is negative” } ], “answer”: “c”, “submitted_answer”: “” }

{ “question_type”: “freeform”, “question”: “Write an if statement condition (just the part after ‘if’) that is True when a variable called score is greater than or equal to 100.”, “answer”: “score >= 100”, “submitted_answer”: “” }