Hello! Welcome to your seventh lesson in our journey through Python and algorithms.
In the last lesson, you learned how to create your own functions—reusable blocks of code that can take inputs (parameters) and produce outputs (return values). This is a powerful way to organize your own code.
But what about common tasks that almost every programmer needs to do, like finding a square root or picking a random number? You don't have to write these functions from scratch every time. Python comes with a vast Standard Library, which is a collection of pre-written code organized into "toolboxes" called modules.
Today, we'll learn how to import and use functions from standard library modules, focusing on two of the most useful ones: math and random. This will greatly expand the range of problems you can solve.
1. What Are Modules and Why Do We Need Them?
Imagine you have a toolbox. Instead of carrying every single tool you own everywhere, you grab the specific set you need for a job—the plumbing tools, the electrical tools, etc.
Modules in Python work the same way. A module is simply a Python file containing functions, variables, and other code, all related to a specific task.
- The
mathmodule contains tools for advanced mathematical calculations. - The
randommodule contains tools for generating random numbers and making random choices.
To use the tools from a module, you first have to tell your program to load it. This is done with the import statement.
# This line makes all the functions in the 'math' module available to our program.
import math
# This line makes the 'random' module available.
import random
Once you've imported a module, you can use its functions with dot notation: module_name.function_name().
Let's see this in action.
2. Performing Advanced Math with the math Module
Python's basic arithmetic operators (+, -, *, /, **) are great, but sometimes you need more. The math module provides functions for trigonometry, logarithms, square roots, and more. It also contains useful constants like Pi.
Let's watch a video that demonstrates how to import the math module and use some of its most common functions.
This video from Bro Code gives a quick and clear overview of the math module. Pay attention to how import math is written at the top of the file and how functions are called using math..
Watch from 06:36 to 08:41. This section covers constants like math.pi and functions like math.sqrt(), math.ceil(), and math.floor().
As you saw, after import math, you can do things like:
- Get the value of Pi:
math.pi - Calculate a square root:
math.sqrt(25)which returns5.0 - Round a number up:
math.ceil(9.1)which returns10 - Round a number down:
math.floor(9.9)which returns9
This image provides a handy summary of several key math functions.

Hands-On Practice 1: Calculate the Hypotenuse
Let's apply this. The formula to find the hypotenuse () of a right-angled triangle given sides and is .
Your task is to write a short program that:
- Imports the
mathmodule. - Creates two variables,
aandb, and assigns them numeric values (e.g., 3 and 4). - Calculates .
- Uses
math.sqrt()to find the square root of the result. - Prints the final value of the hypotenuse.
Click here for the solution
import math
a = 3
b = 4
# You can use the ** operator for exponents (a squared is a**2)
sum_of_squares = (a**2) + (b**2)
# Use the sqrt function from the math module
hypotenuse = math.sqrt(sum_of_squares)
print(f"The hypotenuse of a triangle with sides {a} and {b} is {hypotenuse}")
# Expected output: The hypotenuse of a triangle with sides 3 and 4 is 5.0
3. Introducing Unpredictability with the random Module
The random module is essential for creating games, simulations, and even for certain advanced algorithms. It allows your program to make unpredictable choices. The numbers it generates are technically "pseudo-random" – they are produced by a deterministic formula but are unpredictable enough for most purposes.
Let's explore some of the most useful functions in this module.
Python Tutorial: Generate Random Numbers and Data Using the random Module
Corey Schafer provides an excellent tutorial on the random module. We'll watch a few key segments to cover the essentials.
Please watch the following parts: Importing and Introduction (00:42 - 01:00) Generating Random Integers with randint() (02:25 - 03:31) Choosing from a List with choice() and choices() (03:31 - 05:00) Shuffling a List with shuffle() (07:09 - 08:22) Focus on understanding what each function does and what kind of arguments it needs.
Here's a recap of the key functions you just saw:
random.randint(a, b): Returns a random integer betweenaandb, inclusive of both endpoints. This is perfect for simulating a dice roll (random.randint(1, 6)).random.choice(sequence): Returns a single, randomly chosen element from a sequence (like a list or a string).random.shuffle(list): Randomly re-orders the items in a list. Importantly, this function modifies the list directly and doesn't return a new one.
And here's another helpful summary table for the random module's number-generating functions.

4. Final Challenge: The Number Guessing Game
Let's combine everything you've learned today with your knowledge of loops and conditionals from previous lessons. You will build a classic number guessing game.
Your task:
- Import both the
mathandrandommodules at the top of your file. - Use
random.randint(1, 50)to choose a secret number and store it in a variable. - Use a
whileloop to repeatedly ask the user to guess the number. - Inside the loop:
- Get the user's input and convert it to an integer.
- Use an
if/elif/elseblock to tell the user if their guess is "Too high!", "Too low!", or "Correct!".
- If the user guesses correctly, the loop should end. Print a congratulatory message.
- Bonus: Before the loop starts, calculate the number of optimal guesses using the formula
log₂(n), wherenis the range of numbers (50 in our case). You can usemath.log2(50)for this. Print a message like "The optimal number of guesses is about [result]. Let's see how you do!". Usemath.ceil()to round the result up to the nearest whole number.
This bonus part gives you a glimpse into algorithm analysis. The optimal strategy for this game is a binary search, and log₂(n) tells you roughly how many steps a binary search would take.
Click here for the solution
import random
import math
# Define the range of the game
UPPER_BOUND = 50
# --- Bonus Part ---
# Calculate and print the optimal number of guesses.
# log2(50) tells us how many times we can halve the search space.
optimal_guesses = math.ceil(math.log2(UPPER_BOUND))
print(f"I'm thinking of a number between 1 and {UPPER_BOUND}.")
print(f"The optimal number of guesses is about {optimal_guesses}. Let's see how you do!")
print("--------------------------------------------------")
# 1. Choose a secret number
secret_number = random.randint(1, UPPER_BOUND)
# Initialize a variable for the user's guess
guess = 0
# 2. Loop until the user guesses correctly
while guess != secret_number:
# 3. Get user input
try:
guess_str = input("Enter your guess: ")
guess = int(guess_str)
except ValueError:
print("Invalid input. Please enter a number.")
continue # Skips the rest of the loop and starts the next iteration
# 4. Compare the guess to the secret number
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
# 5. Correct guess
print(f"Correct! The number was {secret_number}.")
print("Thanks for playing!")
Note: The try-except block is included to make the program more robust against non-numeric input. While we haven't formally covered this, it's a good practice to be aware of.
Conclusion
Great job today! You've learned how to harness the power of Python's standard library by importing and using modules. This is a fundamental skill that saves you immense time and effort, allowing you to build on the work of the entire Python community.
Key Takeaways:
- Modules are Python files containing reusable code like functions and variables.
- The
importstatement is used to load a module into your program. - Dot notation (
module.function()) is used to access a module's contents. - The
mathmodule provides tools for advanced mathematical operations (math.sqrt,math.ceil,math.pi, etc.). - The
randommodule provides tools for introducing unpredictability (random.randint,random.choice, etc.).
In the random module examples, you saw functions like random.choice() and random.shuffle() being used on lists. In our next lesson, we will formally introduce lists, one of the most versatile and important data structures in Python. You'll learn how to create, modify, and access data in lists, which will be essential for implementing many of the algorithms we'll study later.