Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Using Python's Built-in Modules

Hello! In our last lesson, we built a crucial bridge between your Python scripts and the outside world by learning how to read from and write to text files. You now have the power to bring data into your programs and save your results. To truly unlock the potential of that data, however, we need a bigger toolbox.

This lesson introduces you to Python's modules. Think of them as pre-packaged toolkits of functions and variables that you can bring into your program to perform specialized tasks without having to write all the code yourself. This is a fundamental concept that moves you from writing small scripts to building powerful applications.

Today, we will focus on two essential built-in modules:

  • The math module, for performing advanced mathematical calculations.
  • The random module, for introducing unpredictability and selection, a cornerstone of simulations, games, and many machine learning algorithms.

By mastering these, you'll gain foundational tools necessary for the more complex data science and AI libraries we'll tackle later.

1. What Are Modules and How Do We Use Them?

So far, you've used Python's built-in functions like print(), len(), and input(). These are always available. However, to keep Python lightweight and organized, a vast amount of its functionality is sorted into collections of code called modules. A library is often a collection of one or more related modules.

To use the functions within a module, you must first explicitly load it into your program's memory using the import statement. This tells Python, "I'm going to need the tools from that specific toolkit."

The GalaxyProject tutorial, "Foundations of Data Science," provides a clear explanation of what libraries are and the different ways you can import them.

Foundations of Data Science / Python - Math / Hands-on

Please read the first two sections of this tutorial.

Start at the beginning and read through the section on Libraries to understand the concept. Then, continue to the next section, Importing a Module, which explains the import module_name syntax. Pay close attention to how you access functions using the . notation (e.g., module_name.function_name). Finally, read the two subsections that show alternative import methods: from...import and import...as. Understanding these three import patterns is key.

To summarize the three main ways to import:

  1. import math: This imports the entire math module. To use a function, you must prefix it with the module name: math.sqrt(9). This is the most common and recommended approach as it avoids naming conflicts.
  2. from math import sqrt: This imports only the sqrt function from the math module. You can then call it directly: sqrt(9). This is useful if you only need one or two functions from a large module.
  3. import random as rd: This imports the entire random module but gives it a shorter alias, rd. You then use the alias as the prefix: rd.randint(1, 10). This is very common with libraries that have long names, like matplotlib.pyplot which is almost always imported as plt.

For the rest of this lesson, we will primarily use the first method (import module_name) as it is the clearest and safest.

2. The math Module: Your Calculator on Steroids

The math module provides access to mathematical functions that are not available in basic Python. This includes things like square roots, trigonometric functions (sine, cosine), logarithms, and important constants like Pi (π).

The following image provides a handy reference for some of the most common functions available in the math module.

A table showing several functions from Python's `math` module, their purpose, and examples of their usage.

The video "Math in Python is easy!" by Bro Code offers a great visual and practical walkthrough of how to use this module.

Math in Python is easy! 📐

This video clearly demonstrates how to import and use the math module for common calculations.

Watch the first part of the video from the introduction to see how to import the module and access the constant math.pi. Then, continue watching the next segment on key functions like math.sqrt(), math.ceil() (round up), and math.floor() (round down).

Your Turn: Calculating the Hypotenuse

Let's apply this. A classic use of the math module is to find the hypotenuse of a right-angled triangle using the Pythagorean theorem: .

Task:
Write a Python script that:

  1. Defines two variables, a and b, representing the two shorter sides of a right-angled triangle. Set a = 5 and b = 12.
  2. Imports the math module.
  3. Calculates the length of the hypotenuse c using the formula.
  4. Prints the result in a user-friendly format, like "The hypotenuse is: 13.0".

Hint: You will need math.sqrt() for the square root. For squaring the numbers, you can use either math.pow(a, 2) or the exponentiation operator a ** 2.




# Your solution here
import math




# 1. Define the sides
a = 5
b = 12




# 3. Calculate the hypotenuse
# a**2 means 'a' to the power of 2
c = math.sqrt(a**2 + b**2)




# 4. Print the result
print(f"The hypotenuse is: {c}")

This simple exercise demonstrates how you can translate a mathematical formula directly into Python code using the math module.

3. The random Module: Embracing Unpredictability

While math is about precise calculations, the random module is about introducing controlled chaos. It allows you to generate random numbers, pick random items from a list, and shuffle sequences. This is incredibly useful for creating simulations, games, and is a critical component in machine learning for tasks like shuffling datasets before training or initializing model parameters.

A flowchart showing some of the core functions available in the `random` module, such as `choice()`, `randint()`, and `shuffle()`.

The video "Generate random numbers in Python" by Bro Code provides another excellent step-by-step guide to the most important functions in this module.

Generate random numbers in Python 🎲

This video walks through the essential functions of the random module with clear, practical examples.

First, watch how to import the module. Then, watch the demonstrations for the following key functions: random.randint() for generating a random integer in a range. random.random() for generating a random float between 0 and 1. random.choice() for picking a random element from a sequence. random.shuffle() for shuffling a list in-place.

Reproducibility with random.seed()

One crucial concept in scientific computing and machine learning is reproducibility. If you are running an experiment, you need to be able to get the exact same "random" numbers again. The random module generates pseudo-random numbers, meaning they appear random but are actually produced by a deterministic algorithm. You can initialize this algorithm with a specific starting value, or seed.

By setting a seed, you ensure that the sequence of random numbers will be identical every time the script is run.

import random

random.seed(42) # Set the seed to a specific number
print(random.randint(1, 100)) # Will always print 82
print(random.randint(1, 100)) # Will always print 15

random.seed(42) # Reset the seed
print(random.randint(1, 100)) # Prints 82 again

This is vital for debugging code that involves randomness and for ensuring that scientific or machine learning results can be reproduced by others.

Your Turn: Build a Number Guessing Game

Now it's time to build a small project that ties together loops, conditionals, and the random module. You will create a classic number guessing game.

The Bro Code video you just reviewed finishes by walking through the creation of this exact game. This aligns perfectly with your preference for seeing projects built from scratch.

Task:

  1. Watch the final segment of the video where the instructor builds the number guessing game (resource_id="[LINK](https://www.youtube.com/watch?v=piJc18hcH0Y)").
  2. After watching, write your own version of the script from scratch.

Your script should:

  1. Import the random module.
  2. Generate a secret random integer between 1 and 100.
  3. Use a while loop to repeatedly ask the user to guess the number.
  4. Use if/elif/else statements to tell the user if their guess is "too high" or "too low".
  5. If the user guesses correctly, print a success message and break the loop.

This exercise is a perfect test of your skills, combining concepts from this and previous lessons into a fun, interactive program.

Conclusion

In this lesson, you've unlocked a new level of capability in Python by learning to use modules. You are no longer limited to the basic built-in functions but can now import specialized toolkits to solve more complex problems.

Key Takeaways:

  • Modules are files containing reusable Python code that you can load into your programs using the import statement.
  • The math module gives you tools for advanced mathematical operations, like math.sqrt() for square roots and constants like math.pi.
  • The random module allows you to introduce controlled randomness, a key tool for everything from games to AI. Key functions include randint(), choice(), and shuffle().
  • Using random.seed() ensures that your "random" results are reproducible, which is essential for testing and scientific applications.

You've now worked with modules that come standard with Python. In our next lesson, we will take the next logical step: learning how to install and use external packages from the wider Python community using a tool called pip. This will open the door to the powerful data science libraries like NumPy and Pandas, bringing you much closer to your goal of building AI applications.

Can't find a good explanation? Sign up and we'll make it for you

Sign up