Skip to content

8 min read

American Corners

Conditionals and randomness

Two things Python is fussy about

Before your robot on the screen can make a choice, it helps to know two rules Python never bends.

The first is case sensitivity. Imagine an online shop where you search for a laptop. Whether you type "laptop", "LAPTOP" or "Laptop", the same results come up, because the search ignores capital letters. Python is not so forgiving. To Python, Score and score are two completely different names. If you save a value in one and then read from the other, you get an error or the wrong answer. So pick a spelling for each name and stay with it.

The second rule is indentation. Python decides which lines belong together by the spaces at the start of each line. The lines pushed in under an if are the ones that run when the condition is true.

if 5 > 2:
    print("Five is greater than two!")

The indent is not decoration. Remove it and Python stops, because it can no longer tell which lines are inside the block. Four spaces is the usual amount; the exact number is up to you, as long as you are consistent.

Random numbers and the Turtle Race

A program that always does the same thing is predictable. Games need surprise, and so does any model that explores different values. Python brings in chance with the random module.

import random

print(random.random())       # a decimal between 0.0 and 1.0
print(random.randint(0, 22)) # a whole number from 0 to 22

random.random() gives a decimal from 0.0 up to 1.0. random.randint(a, b) gives a whole number from a to b, and both ends are included. Run these a few times and you will see different results each time.

A single random number is often all a decision needs. Here one dice roll decides whether to print "high" or "low":

import random

roll = random.randint(1, 6)
if roll > 3:
    print("high")
else:
    print("low")

Each time you run it the roll changes, so the answer changes with it. This same spark of chance is what powers a game like the Turtle Race: give each turtle a random step size and no one can say in advance which one reaches the edge first.

Making a decision with if and else

An if statement checks a question that is either true or false, and runs its indented block only when the answer is true.

num = 5
if num < 10:
    print("num is smaller than 10")
print("This line always runs")

The first message appears because num really is smaller than 10. The last line sits at the outer level, so it runs no matter what.

Often you want one thing to happen when the answer is true and something else when it is false. That is what else is for.

num = 5
if num > 10:
    print("number is greater than 10")
else:
    print("number is less than 10")

Exactly one of the two branches runs. Here num is not greater than 10, so Python prints "number is less than 10" and skips the other branch entirely.

elif, nesting, and combining conditions

When there are more than two cases, elif (short for "else if") lets you test them in order. Here is a worked example: how many days are in a given month, taking leap years into account.

year = int(input("Enter the year: "))
month = int(input("Enter the month: "))

is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

if month in (1, 3, 5, 7, 8, 10, 12):
    print("There are 31 days in this month")
elif month in (4, 6, 9, 11):
    print("There are 30 days in this month")
elif month == 2:
    if is_leap:
        print("There are 29 days in this month")
    else:
        print("There are 28 days in this month")
else:
    print("That is not a valid month")

Python checks the branches from top to bottom and stops at the first one that is true. Notice February: inside its branch there is a second if, nested one level deeper, that chooses between 28 and 29 days. An if inside another if lets you ask a follow-up question only when the first answer sends you there.

The leap-year line also shows how to join questions. and is true only when both sides are true. or is true when at least one side is true. not flips true and false. A year is a leap year when it divides evenly by 4 and not by 100, or when it divides evenly by 400.

You now have everything for a game of Rock, Paper, Scissors: the computer picks at random, you type your choice, and conditions decide the winner.

import random

choices = ["rock", "paper", "scissors"]
computer = random.choice(choices)
you = input("rock, paper or scissors? ")

if you == computer:
    print("Tie!")
elif (you == "rock" and computer == "scissors") or \
     (you == "paper" and computer == "rock") or \
     (you == "scissors" and computer == "paper"):
    print("You win!")
else:
    print("You lose!")

Lab

Type the Rock, Paper, Scissors program and play a few rounds. Then extend it: keep a score, or add "lizard" and "spock" and work out the new winning conditions with and and or.

Check yourself

  1. To Python, are Score and score the same name or two different names, and why does that matter?
  2. What does random.randint(1, 6) give you, and how is it different from random.random()?
  3. In the days-in-a-month example, why is elif a better fit than writing several separate if statements?

Where this lesson comes from

Built from

  • Programming in a Data World: Lecture 2 deck (randomness, conditionals) and Lecture Notebook

alphaPlan courses are built from taught programmes rather than invented for the web. Where a claim rests on an outside standard or a reported case, it is named above so you can check it rather than take our word for it.

This course was developed by alphaPlan Center from programs delivered in partnership with the American Corners network.

Found something unclear, outdated or improvable? Suggest an improvement