Skip to main content
Informatik.uz
Chapter 3. Functions and Modules

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.

Topic 10 of 111 min readUpdated October 27, 2026
All topics (10 of 11)

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 math module: sqrt, pi, floor, ceil and others.
  • The random module: randint, choice, shuffle.
  • from module import name lets you use a function without the module name.

Practice tasks

  1. Let the user enter a radius; with math.pi the program prints the area of the circle and the circumference.
  2. Write a program that rolls two dice with random.randint(1, 6) and prints their sum.
  3. Create a “Guess the number” game: the program thinks of a number from 1 to 50, a while loop continues until the guess is right and counts the attempts.

Review questions

Test yourself: think first, then reveal the answer.

  1. 1What is a module and how do we connect it to a program?
    A module is a file with ready-made functions; it is connected with a command such as `import math`.
  2. 2Which values can `random.randint(1, 6)` return?
    1, 2, 3, 4, 5 or 6; both ends are included.

0 of 11 topics completed

Sign in to mark
Informatika 9-sinf darsligi muqovasi
In the textbookInformatics — Grade 9