Python If Statements for Kids: Teaching Programs to Decide

ยท 2 min read ยท By the Tiny Coderz team

Every day you make decisions: if it's raining, take an umbrella; otherwise, don't. Programs make decisions in just the same way, with something called an if statement.

The simplest if

weather = "rain"

if weather == "rain":
    print("Take an umbrella!")

Read this aloud: "If weather equals rain, print take an umbrella." Three things to notice:

  • == (two equals signs) means "is it the same as?" A single = puts a value in a variable; a double == asks a question.
  • The line ends with a colon.
  • The line below is indented. That's what runs when the condition is true.

Adding else

What if it isn't raining?

weather = "sun"

if weather == "rain":
    print("Take an umbrella!")
else:
    print("Wear sunglasses!")

Exactly one of the two lines will run.

More than two choices: elif

age = 8

if age < 5:
    print("Nursery")
elif age < 12:
    print("Primary school")
else:
    print("Secondary school")

elif means "else if." Python checks each condition in order and runs the first one that is true.

Comparing things

  • == is it equal to?
  • != is it not equal to?
  • < is it less than?
  • > is it greater than?
  • <= and >= mean less than or equal, and greater than or equal.

Comparisons give back True or False, and an if runs only when the answer is True.

Combining conditions

Use and, or and not to make richer questions:

age = 9
has_ticket = True

if age >= 8 and has_ticket:
    print("Come on in!")

Both parts must be true for and. With or, only one needs to be.

A small guessing game

secret = 7
guess = int(input("Guess my number: "))

if guess == secret:
    print("You got it!")
elif guess < secret:
    print("Too low!")
else:
    print("Too high!")

input always gives back text, so int(...) turns what the player typed into a number.

Common mistakes

  • Writing = when you meant ==.
  • Forgetting the colon after the condition.
  • Getting the indentation wrong, so the wrong lines run.
  • Comparing text with a different capital letter: "Rain" is not "rain".

Try it

  1. Write a program that asks for a number and says whether it's even or odd. (Hint: number % 2 == 0.)
  2. Ask for a password and print "Welcome" only if it matches.
  3. Grade a score: 90 or more is "A", 70 or more "B", otherwise "Keep practising."

If statements combine beautifully with loops. Together they let you build quizzes, games and much more. Practise in the Conditionals lesson.

Try Python Fundamentals with your child

Every lesson in Python Fundamentals opens with an animated explanation, then a short practice. You can read a full sample lesson with no account.

Keep reading