Please enable JavaScript to use CodeHS

Python Tutorial

Randomization in Python

Dice games, shuffled playlists, surprise loot drops - the fun in a program often comes from not knowing what happens next. Learn to roll the dice with Python's random module.

python ~20 min Beginner friendly
The Big Idea

Why make programs random?

So far, your programs have probably done the exact same thing every time you run them. That's great for a calculator - but pretty boring for a game! Randomization is what makes a dice game exciting, a deck of cards worth shuffling, and a video game enemy hard to predict.

Randomness shows up in serious places too: scientists use random numbers to simulate real-world behavior (like predicting how different species might interact in the wild), and it plays a big role in physics modeling, cryptography, and even art and music. Anywhere the real world is unpredictable, random numbers help a program act like the real world.

Think of it this way: without randomness, a computer is a very fast robot that always follows the same script. With randomness, it can surprise you - and surprises are what games are made of.

Setup

Importing the random module

Python doesn't turn on its randomness powers automatically. They live in a library called random. A library is a collection of functions and programs written by other people that you can use in your own code - no need to reinvent the dice!

To use a library, you import it with one line at the very top of your program:

main.py
import random

# now every function in the random library is ready to use

That single line loads all of the functions from the random library so they can be used in your program without any hassle. To call one of those functions, you write random. before its name - that tells Python "this function comes from the random library, not from my own file."

Good to know: the two random functions you'll use most on CodeHS are randint and choice. Curious what else is in there? The official Python documentation lists everything.


Rolling Numbers

random.randint(a, b)

random.randint(low, high) hands you a random whole number between low and high. Here's the part people get wrong all the time, so let's say it loudly:

Both endpoints are included! random.randint(1, 5) can give you 1, 2, 3, 4, or 5. That's different from range(1, 5), which stops before 5. randint is inclusive on both ends.

Try running this program a few times - notice that the answer changes:

main.py
import random

num = random.randint(1, 5)
print(num)  # a random number from 1 to 5, including both 1 and 5
Console (one possible run - yours may differ!)
4

A six-sided die? That's just random.randint(1, 6). A coin flip? random.randint(0, 1). A lottery ball from 1 to 99? You get the idea.

Interactive

The Random Lab

Time to play. This lab has three stations - roll some dice, explore exactly which numbers randint can produce, and let Python pick from a list you write yourself.

Each die is one call to random.randint(1, 6). Roll a few times - do the dice ever agree? Do they ever have to?

Press Generate to get a number.



Stuck deciding what's for lunch? Now Python can decide for you. Try your own list: pets, weekend plans, team names...

Your Turn

Practice: lotto machine

1

Lucky Lotto Numbers

A board game company is creating a new lotto game where users press a button and get three numbers from 1 to 10. Write a program that gets three random numbers from 1 to 10 and prints them to the console.

main.py (starter code)
# random needs to be imported in order to use its functions
import random

# get three random numbers from 1-10

# print the numbers to the console
solution.py
# random needs to be imported in order to use its functions
import random

# get three random numbers from 1-10
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
num3 = random.randint(1, 10)

# print the numbers to the console
print(num1)
print(num2)
print(num3)
Console (one possible run - yours may differ!)
7
1
10

Notice we call randint three separate times. One call gives one number - each call is its own fresh roll, so the three numbers can repeat (a lotto with 1, 1, 1 is legal, just unlucky).


Picking Things

random.choice()

Numbers are great, but sometimes you want Python to pick a thing: a word, a letter, a player. Like randint, choice randomly picks - but instead of picking from a number range, it picks one element from a sequence. It works on strings:

main.py
import random

element = random.choice("abcdefg")
print(element)  # prints one character from the string "abcdefg"
Console (one possible run - yours may differ!)
d

And it works on lists:

main.py
import random

list_item = random.choice(["Merry", "Had", "A", "Little", "Lamb"])
print(list_item)  # prints one item from the given list
Console (one possible run - yours may differ!)
Little

Which one do I use? Need a random number in a range? Use randint. Need a random item from a collection you already have? Use choice.

Your Turn

Practice: Bingo caller

2

B-52! The Bingo Key Generator

The game company you work for also wants to create an online version of Bingo. They've asked you to create a program that generates a random number from 1 to 99 and a letter from the sequence "BINGO". The final value printed to the console should be in the form Letter - Number. For example, a valid Bingo key would be B-52.

main.py (starter code)
# random needs to be imported in order to use its functions
import random

bingo = "BINGO"

# Generate a random number from 1-99

# Generate a random letter from bingo

# print generated sequence to console
solution.py
# random needs to be imported in order to use its functions
import random

bingo = "BINGO"

# Generate a random number from 1-99
number = random.randint(1, 99)

# Generate a random letter from bingo
letter = random.choice(bingo)

# print generated sequence to console
print(letter + "-" + str(number))
Console (one possible run - yours may differ!)
G-17

Two random tools, one program: randint rolls the number, choice picks the letter. We wrap the number in str() so it can be glued onto the letter with +.


Combine and Conquer

Randomness in loops and ifs

Random numbers get really powerful when you mix them with the control structures you already know. Put a randint call inside a loop and every trip through the loop gets a fresh roll. Add an if statement and your program can react differently depending on what luck delivers:

main.py
import random

# Roll a die 5 times and celebrate every 6
for i in range(5):
    roll = random.randint(1, 6)
    if roll == 6:
        print("You rolled a 6! Jackpot!")
    else:
        print("You rolled a " + str(roll))
Console (one possible run - yours may differ!)
You rolled a 3
You rolled a 6! Jackpot!
You rolled a 1
You rolled a 4
You rolled a 6! Jackpot!

Because the randint call sits inside the loop body, it runs again on every repeat - five loops, five different rolls. If we had rolled once before the loop instead, we'd print the same number five times. Where you put the random call matters!

Challenge yourself: can you change the program to count how many jackpots you got out of 5 rolls? (Hint: it's just like the vowel counter from the for loops tutorial - start a counter at 0 and add 1 inside the if.)


Code

A random example

Randomness makes programs unpredictable and fun. This program rolls a die and picks a random choice.


Check Yourself

Quick quiz

1. Which values can random.randint(1, 4) return?

2. What must appear at the top of your program before you can call random.randint(1, 6)?

3. You want Python to randomly pick one team name from ["Rockets", "Wolves", "Comets"]. Which line does it?

Keep learning Python

You can now make programs that surprise you. Combine randomness with math and loops to build dice games, simulations, and number guessers - here's where to go next.