The Python library
We do not have to write everything from scratch each time: the standard library that comes with Python has ready modules, for example math (mathematics), random (random numbers), datetime (date and time), turtle (drawing), tkinter (windows). A module must be loaded before it is used. There are three ways: import random – the function is called with the module name (random.randint(1, 6)), which makes the code easy to read; from random import randint – only the needed function is taken and called by its name; from random import * – everything is taken, but the names get mixed with your own, so it is not recommended. random.randint(a, b) gives a whole number from a to b (b included); random.randrange(a, b, k) goes from a to b (b not included) with step k; random.random() gives a fraction from 0 to 1. Install additional libraries (through pip) only from the official, trusted source and with an adult’s help.
| Way | Call |
|---|---|
| import random | random.randint(1, 6) |
| from random import randint | randint(1, 6) |
| from random import * | not recommended |
Pupils devised a way to give random numbers for a team game: they mixed numbered paper slips and drew one. In programs, ready random-number modules do the same job.
Game developers, statisticians and programmers use random numbers for games, tests and sampling.
Toss a coin 20 times and record heads and tails in a table. Did you get exactly 10 of each?
1import random 2x = random.randint(1, 6) 3print(1 <= x <= 6) 4 5import random 6x = random.randrange(10, 31, 5) 7print(x % 5 == 0 and 10 <= x <= 30)
True True
1import random 2from random import randint 3print(random.randint(5, 5), randint(7, 7))
5 7
“Random choice”: using random.randint for the numbers in the class list, the group writes a “who goes to the board today” program; the program is run several times and the different results are observed.