The built-in random module lets you produce random numbers; dice rolls, coin tosses, shuffled decks, noise for a simulation.
Like any standard module, it is brought in with import:
import random
print(random.int(1, 6)) // a number from 1 to 6
An important aspect to know from the start is that any number generated from the module isn’t truly random.
They are pseudo-random.
What this means is that they come from a mathematical procedure that, given a certain starting point, produces a long sequence of numbers that looks random and passes common statistical tests, but is entirely determined by that starting point. This is exactly what is wanted for games, simulations, sampling and testing, and it has one valuable consequence that we will use below. It also naturally means that the module is not suitable for anything related to security, such as passwords, tokens or keys; someone who knows how the generator works and sees enough of its output could predict what number may come next. For those purposes, a source of randomness provided by the operating system can be used.
Random Numbers
The basic function is random.random.
It takes no arguments and returns a number from zero up to, but not including, one. Every other function of the module is a different way of presenting the same source, and random.random is the building block for anything that the module does not provide:
print(random.random()) // 0.3917..., for example
For numbers in another interval, random.number takes the two limits, and returns a number that is at least the first and less than the second. It is random.random scaled and shifted, which is the same as writing the arithmetic yourself:
var temperature = random.number(-5, 30) // any value from -5 up to, but not including, 30
Random Integers
Most programs want whole numbers, and for them there is random.int.
It takes a lower and upper bound, and, unlike the functions above, both bounds are included in the result:
var die = random.int(1, 6) // 1, 2, 3, 4, 5 or 6
var coin = random.int(0, 1) // 0 or 1
The first bound must not be greater than the second, and the numbers are expected to be whole and of moderate size.
Be careful with the difference; the end of a range is excluded, and the upper bound of random.int is not. Writing random.int(0, n) for a number that is to be used as an index into a list of n items would sometimes give an out of bounds index. For that, use random.int(0, n - 1), or, better, the functions random.choice described below.
When what is needed is a choice with equal chances, random.bool returns true or false, each with a probability of one half:
if random.bool()
{
print("heads")
}
else
{
print("tails")
}Random from a Range
The function random.range picks a random value from a sequence of numbers, described in the same way as a range of the language, with an excluded end.
It accepts the same three forms: only an end, with start at zero and the step at one; a start and an end; or a start, an end and a step. A range value can also be given, directly:
print(random.range(10)) // 0 to 9
print(random.range(5, 10)) // 5 to 9
print(random.range(0, 100, 10)) // 0, 10, 20, ... or 90
print(random.range(1..7)) // 1 to 6
print(random.range(10, 0, -2)) // 10, 8, 6, 4 or 2
The step makes it possible to pick evenly spaced values, which random.int cannot do. If the range is empty, as in random.range(5, 5), there is nothing to choose from, and the result is an error.
Choosing and Shuffling
Two functions work with lists.
The function random.choice returns an item of a list picked at random, all items having the same chance. The list must have at least one item:
var colors = ["red", "green", "blue"]
print(random.choice(colors))The function random.shuffle rearranges the items of a list in a random order.
It changes the list that it is given, and does not make a copy, so, as always with lists, anyone else who holds the same list will see the new order. When the original must be kept, shuffle a copy:
var deck = ["A", "K", "Q", "J", "10"]
var hand = deck.copy()
random.shuffle(hand)
print(hand) // for example [Q, A, 10, K, J]
Picking several different items out of a list, such as dealing cards, is then a matter of shuffling and taking the first ones, which is shorter and less error-prone than choosing at random and checking repetitions.
Seeds
The generator used by this module has an internal state, that every number it produces changes. The state at the beginning is determined by a number called the seed.
When the random module is imported, it is seeded with the current time, so every run of a program starts from a different state and gives different results.
The function random.seed sets the seed explicitly.
Two sequences started with the same seed are exactly the same, which, for a generator of “random” numbers, is at first surprising:
random.seed(7)
var a = [random.int(1, 100), random.int(1, 100), random.int(1, 100)]
random.seed(7)
var b = [random.int(1, 100), random.int(1, 100), random.int(1, 100)]
print(a) // for example [48, 91, 13]
print(b) // the same three numbers again
This is of course the main reason to seed deliberately.
A test that depends on a random data can be repeated and checked, a bug that shows only with some values can also be reproduced, and a game can offer the same level to anyone who types the same number. For ordinary use, there is no need to call random.seed at all, and a program that seeds with a constant by accident will get the same “random” numbers every run.
Note that the sequence produced for a given seed is a property of the interpreter’s version or implementation, and it may not be the very same in a different one, so seeds are best used to reproduce something within the same installation, and not to store or exchange results.
An Example
We finish with a simulation.
The program rolls two dice six thousand times and draws a histogram of the sums, using a bar of # for every fifty rolls. It shows something that is not obvious at first; though each die is equally likely to give any of its faces, the sums are not, because there are more ways of making a seven than a two.
The seed is fixed, so that the program prints the same histogram every time.
// dice.tea
import math, random
random.seed(2026)
var counts = {}
for var total in 2..13
{
counts[total] = 0
}
for var roll in 0..6000
{
var total = random.int(1, 6) + random.int(1, 6)
counts[total] += 1
}
for var total in 2..13
{
var bar = Buffer.new()
for var i in 0..math.floor(counts[total] / 50)
{
bar.put("#")
}
var label = total < 10 ? " ${total}" : "${total}"
print("${label}: ${bar.tostring()}")
}$ tea dice.tea
2: ##
3: ####
4: ######
5: ########
6: ###########
7: ##############
8: ###########
9: ########
10: ######
11: ####
12: ##
The exact bars depend on the seed and the version of the interpreter, but the shape is always the same; a pyramid with its peak at seven.
Changing the seed, or removing the call to random.seed, changes the details of every run and leaves the pyramid in place. The map holds one counter for each possible sum, the for loops use ranges whose end is excluded, and the buffer is the efficient way of assembling each bar.
This is the last of the chapters that describe a module for general use. The next one, on the debug module, is dedicated to the tools that help inspect the internals of some interpreter structures.