Menu

Random Library

Random values in calculations and output

A random value is an ordinary number once it has been generated, so you can use it in arithmetic and in output in exactly the same way as a value you typed into the program yourself. You can add a constant (a fixed value that never changes) to it, multiply it by a constant, or add it to a second random value produced by a separate call.

Combining random values with fixed values

A school art club sells raffle strips at £2 each. The number sold on Saturday is a random whole number from 12 to 25, produced by random.randint(12, 25). Multiplying that value by the constant 2 gives the money taken, and taking away the constant 18 that the club paid for the prize gives the profit. One run might sell 19 strips, giving £38 taken and £20 profit, while another run might sell 21 strips, giving £42 taken and £24 profit.

Two random values can be added together in the same way. A bakery sells a random number of white loaves, from 30 to 50, and a random number of brown loaves, from 20 to 40; adding the two values gives the total number of loaves sold on that run.

Showing random values in output

Printing a random value makes the output change from one run to the next, because the value is not known until the program runs. Store the generated value in a variable as soon as it is made, so the same number is used in every calculation and in the output; calling randint again gives you another value, so the printed figures might no longer match the calculation.

import random

saturday = random.randint(12, 25)
money = saturday * 2
profit = money - 18
print("Strips sold:", saturday)
print("Money taken:", money)
print("Profit:", profit)

Output:

Strips sold: 24
Money taken: 48
Profit: 30

Run the program twice and you will see two different sets of printed numbers, even though nothing in the code changed.

Practise this