Menu

Random Library

The random() function

random.random() takes no arguments — the brackets stay empty — and returns a random real number, one that can have a decimal part. Every value it produces is at least 0.0 and less than 1.0: 0.0 itself is possible, but exactly 1.0 never is.

import random

print("First decimal:", random.random())
print("Second decimal:", random.random())

Output:

First decimal: 0.9664535356921388
Second decimal: 0.4407325991753527

Each call produces a new value, so the two lines will almost certainly show different decimals. On its own, a number like 0.4731 is not much use, so it usually gets scaled.

Scaling to a range you choose

Suppose you want a real number between 2.0 and 6.0 instead. To scale the value, multiply it by the width of your target range, then add the lower bound. Multiplying stretches the 0-to-1 span so it is as wide as your range, and adding the lower bound slides that span up to start at the right place.

The pattern is low + random.random() * (high - low).

import random

low = 2.0
high = 6.0
rainfall = low + random.random() * (high - low)
print("Rainfall (mm):", rainfall)

Output:

Rainfall (mm): 5.865814142768555

Which values can come out

ExpressionSmallest possibleLargest possible
random.random()0.0just under 1.0
low + random.random() * (high - low)lowjust under high

Because 0.0 is possible, a scaled value can land exactly on the lower bound. Because 1.0 is not possible, it can creep very close to the upper bound but never reach it, so a rainfall of exactly 6.0 mm will never appear. That is different from random.randint, whose highest value is possible.

Practise this