☰ Contents · Computing

Library, modules and the math module

Lessons 51–52 · 2 lessons · M. R. Fayziyeva, D. M. Sayfurov, N. S. Xaytullayeva. Informatics and Information Technologies, Grade 9. “Nashriyot uyi Tasvir”, Tashkent, 2020
51

The Python library

Textbook: pp. 100–102
GoalKnows the concepts of a library and a module, tells the ways of importing a module apart, and uses the randint, randrange and random functions of the random module.
New words
module: a file with ready code (functions, constants) that can be used in other programs · modulstandard library: the set of modules that comes with Python · standart kutubxonaimport: loads a module (or one of its functions) into the program · importrandom: the module that gives random numbers · random
Explanation

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.

Worked examples
A random number: import random ⏎ x = random.randint(1, 6) ⏎ print(1 <= x <= 6) x is different each time, but the condition is always true: True. A range with a step: import random ⏎ x = random.randrange(10, 31, 5) ⏎ print(x % 5 == 0 and 10 <= x <= 30) one of the numbers 10, 15, 20, 25, 30 comes up, so True is printed.
Ways of importing: import random ⏎ from random import randint ⏎ print(random.randint(5, 5), randint(7, 7)) randint(5, 5) can give only 5 and randint(7, 7) only 7; the first is called with the module name and the second directly.
Class activity

“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.

Practice
1
If import random is written, how is the randint function called?
2
Write a program that prints a random number from 1 to 6 (rolling a die).
3
How many different values can random.randrange(3, 40, 4) give?
4
Why is using from random import * not recommended?