Modules: math and random
A module is a collection of ready-made functions. We use math for calculations and random for random numbers to write fun game programs.
All topics (10 of 11)
Chapter 1. Python Basics
Chapter 2. Lists and Strings
Chapter 3. Functions and Modules
Chapter 4. Working with Files
Not all of Python’s features sit in one place; they are divided into modules. A module is a file that stores ready-made functions and values. It is connected with import: import math. After that a function is reached through the module name: math.sqrt(25) gives 5.0.
The math module is made for mathematical calculations. It offers math.sqrt(x) (square root), math.pi (the number π, about 3.14159), math.floor(x) (round down), math.ceil(x) (round up), math.sin(x) and more. For example, the area of a circle of radius r is found with math.pi * r * r.
The random module provides random values. random.randint(1, 6) returns an integer from 1 to 6 (both ends included), just like a die. random.choice(names) picks a random item from a list, and random.shuffle(names) shuffles it. Because a computer formula produces these numbers, they are called pseudo-random.
You can also take just the function you need: after from math import sqrt it is called without the module name, as sqrt(16). Example: a “Guess the number” game. The computer thinks of secret = random.randint(1, 100), the user guesses, and the program hints “higher” or “lower”. Do not name your own file random.py or math.py, or the modules will get mixed up.
Key takeaways
- A module is a set of ready-made functions; it is connected with
import. - The
mathmodule:sqrt,pi,floor,ceiland others. - The
randommodule:randint,choice,shuffle. from module import namelets you use a function without the module name.
Practice tasks
- Let the user enter a radius; with
math.pithe program prints the area of the circle and the circumference. - Write a program that rolls two dice with
random.randint(1, 6)and prints their sum. - Create a “Guess the number” game: the program thinks of a number from 1 to 50, a
whileloop continues until the guess is right and counts the attempts.
Review questions
Test yourself: think first, then reveal the answer.
1What is a module and how do we connect it to a program?Show answerHide answer
A module is a file with ready-made functions; it is connected with a command such as `import math`.2Which values can `random.randint(1, 6)` return?Show answerHide answer
1, 2, 3, 4, 5 or 6; both ends are included.
0 of 11 topics completed
Sign in to mark