livepython.net
CHAPTER 18Python Modules
18.3  RANDOM

Python random Module: randint, choice and shuffle

Random Numbers in Python: random.randint()

The random module makes values your program can't know in advance. random.randint(a, b) gives back a random whole number from a to b, and both ends are included.

import random

roll = random.randint(1, 6)
print("You rolled", roll)   # Output: You rolled 4 (or any number from 1 to 6)

Run it twice, and you'll likely see two different numbers. That's the whole point! Because the output changes every run, the live example below prints something that doesn't change: a check that the roll is in range.

PYTHONedit me
import random

roll = random.randint(1, 6)
print(1 <= roll <= 6)
print(type(roll))
OUTPUT
True
<class 'int'>

Think of it like rolling a real dice. You know it lands on 1, 2, 3, 4, 5 or 6. You just don't know which one until you roll.

The rules

  • random.randint(1, 6) can give 1, 6, or anything between. Both ends are in.
  • That's different from range(1, 6) in chapter 10, which stops before 6.
  • Each call is a new roll: call it again for a new number.
  • The first number must not be bigger than the second.

Roll many times

Put randint() in a for loop to roll again and again. Every number lands in range, even though you can't know which:

PYTHONedit me
import random

all_good = True
for i in range(100):
    roll = random.randint(1, 6)
    if roll < 1 or roll > 6:
        all_good = False
print("100 rolls, all from 1 to 6:", all_good)
OUTPUT
100 rolls, all from 1 to 6: True

Avoid: the numbers the wrong way round

PYTHONedit me
import random

print(random.randint(6, 1))
OUTPUT
ValueError: empty range in randint(6, 1)

"Empty range" means there are no numbers from 6 up to 1. Put the small number first: randint(1, 6).

Common beginner doubt: "Are these numbers truly random?" Not quite. The computer works them out with a clever formula, so they're called pseudo-random ("pseudo" means "pretend"). For games and practice, they're random enough.

random.randint(a, b) gives a random whole number from a to b, both ends included.

your turnPick the right idea

Which numbers can random.randint(1, 3) give back?

Think about it, then pick one.
your turnType the output

Type what this prints

import random n = random.randint(1, 10) print(n >= 1 and n <= 10)
Read the code line by line, then type the output exactly.

random.choice() and random.shuffle(): Pick and Mix a List

random.choice() picks one random item from a list. random.shuffle() mixes up the order of a list's items, right inside the list.

import random

names = ["Sunny", "Rocky", "Lucky"]
print(random.choice(names))   # Output: Rocky (or Sunny, or Lucky)
random.shuffle(names)
print(names)                  # Output: ['Lucky', 'Sunny', 'Rocky'] (any order)

Think of it like a hat with names on paper slips. choice() pulls out one slip. shuffle() shakes the hat, and every slip is still in there, in a new order.

The live example prints only what can't change: the pick is always from the list, and shuffling keeps every item.

PYTHONedit me
import random

names = ["Sunny", "Rocky", "Lucky"]
winner = random.choice(names)
print(winner in names)
random.shuffle(names)
print(len(names))
print(sorted(names))
OUTPUT
True
3
['Lucky', 'Rocky', 'Sunny']

The rules

  • random.choice(items) gives back one item. The list doesn't change.
  • choice() works on strings too: random.choice("ABC") gives one letter.
  • random.shuffle(items) changes the list itself and gives back None, like sort() in chapter 9.
  • random.sample(items, 2) gives back a new list of 2 different items, with no repeats.

Avoid: storing what shuffle() gives back

PYTHONedit me
import random

cards = ["A", "K", "Q"]
cards = random.shuffle(cards)
print(cards)
OUTPUT
None

shuffle() mixed the list, then gave back None, and that None replaced the list. Call it on a line by itself: random.shuffle(cards).

Avoid: choice() from an empty list

PYTHONedit me
import random

print(random.choice([]))
OUTPUT
IndexError: Cannot choose from an empty sequence

There is nothing in the hat to pick! Check that the list isn't empty first, with if items:.

Common beginner doubt: "Can choice() pick the same item twice?" Yes, if you call it twice: each call is a fresh pick from the full list. Use sample() when the picks must be different.

choice() picks one item; shuffle() mixes the list itself and gives back None.

your turnPredict the output

What will this print?

import random nums = [1, 2, 3] result = random.shuffle(nums) print(result)
Your turn! What will this code show on the screen?
your turnFill the gap

Pick one random winner from the list

import random names = ["Sunny", "Rocky", "Lucky"] winner = random.?(names) print(winner in names)

It should print: True

Which piece makes this code work?

random.random() and random.uniform(): Random Decimals

random.random() gives back a random decimal from 0 up to, but not including, 1. random.uniform(a, b) gives a random decimal between a and b.

import random

print(random.random())          # Output: 0.6394267984578837 (it changes every run)
print(random.uniform(1.5, 2.5)) # Output: 1.7249... (it changes every run)

Think of it like a spinner with a dial from 0 to 1. Spin it, and the arrow stops somewhere on the dial. It can stop on 0, but it never reaches the very end, 1.

PYTHONedit me
import random

x = random.random()
print(0 <= x < 1)
height = random.uniform(1.5, 2.5)
print(1.5 <= height <= 2.5)
print(type(x))
OUTPUT
True
True
<class 'float'>

The rules

CallGives backExample
random.randint(1, 6)a whole number, both ends in4
random.random()a float from 0 up to (not including) 10.27...
random.uniform(1.5, 2.5)a float between the two numbers2.03...

A real job: a chance in percent

"A 30% chance of rain" means: out of 100 days like this, about 30 have rain. random.random() is below 0.3 about 30% of the time, so it's perfect for chances:

import random

if random.random() < 0.3:
    print("It rains today")
else:
    print("No rain today")

Run it many times, and you'll see rain about 3 times out of 10. Games use this for lucky hits and surprise prizes.

Show a random decimal neatly

A random float has many digits. Round it when you print, with :.2f from chapter 5. Here the price changes every run, but its length doesn't:

PYTHONedit me
import random

price = random.uniform(10, 20)
text = f"{price:.2f}"
print(len(text))
OUTPUT
5

Common beginner doubt: "Why does random() have no numbers in the brackets?" Its range is always 0 to 1. Multiply it to stretch it: random.random() * 100 gives a decimal from 0 up to 100.

random.random() gives a float from 0 up to 1; random.uniform(a, b) gives one between a and b.

your turnPick the right idea

Which line gives Lucky a 50% chance to win?

Think about it, then pick one.
your turnPredict the output

Remember range() from chapter 10?

total = 0 for i in range(1, 4): total += i print(total)
Your turn! What will this code show on the screen?

random.seed(): Get the Same Random Numbers Every Run

random.seed(n) sets the starting point of the random numbers. After the same seed, Python gives the same "random" numbers, in the same order, every single run.

PYTHONedit me
import random

random.seed(7)
print(random.randint(1, 6), random.randint(1, 6), random.randint(1, 6))

random.seed(7)
print(random.randint(1, 6), random.randint(1, 6), random.randint(1, 6))
OUTPUT
3 2 4
3 2 4

Run it as many times as you like: it's always 3 2 4, twice. Remember the "pseudo-random" formula from the first lesson? The seed is where that formula starts. Same start, same numbers.

Think of it like a playlist on shuffle with a saved order. Pick saved order number 7, and the songs always come in the same "random" order. Pick a different number, and you get a different order.

The rules

  • Call random.seed(n) before the random calls. Any whole number works as n.
  • The same seed always gives the same numbers, in the same order.
  • A different seed gives different numbers.
  • No seed at all: Python picks a new start each run, so the numbers change.

Why would you want that?

  • Testing. A program that prints random numbers can't be checked: the right output changes every time. With a seed, the output is fixed, so you (or a test) can check it. The practice questions in this chapter use a seed for exactly this reason.
  • Finding bugs. If a game breaks only with some rolls, a seed lets you play those same rolls again.
  • Sharing. A friend who uses the same seed sees the same results as you.
PYTHONedit me
import random

random.seed(42)
first = random.choice(["Sunny", "Rocky", "Lucky"])
random.seed(42)
second = random.choice(["Sunny", "Rocky", "Lucky"])
print(first == second)
print(first)
OUTPUT
True
Lucky

Common mistake: a seed in a real game

With random.seed(1) at the top of a dice game, every game rolls the same numbers. That's great for testing, but a player will soon notice! Remove the seed when the game is finished.

Common beginner doubt: "Will seed 7 give 3 2 4 on every computer?" On the same version of Python, yes. A very different version may give other numbers, so keep the seed and the expected output together.

The same random.seed(n) gives the same random numbers every run: perfect for testing.

your turnType the output

Type what this prints

import random random.seed(5) a = random.randint(1, 100) random.seed(5) b = random.randint(1, 100) print(a == b)
Read the code line by line, then type the output exactly.
your turnPick the right idea

Why do the practice questions in this chapter use random.seed()?

Think about it, then pick one.

Practice: random

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 165.Python Program to Roll Two Dice Using random.seedEasySolve
  2. 166.Python Program to Make a Random Number Guessing GameMediumSolve