Chapter 16: Using External Code - Modules and the Python Standard Library

So far, you've been writing all of your code in a single file. As your projects grow, this can become unwieldy. More importantly, you don't have to write everything from scratch! Python comes with a massive collection of pre-written code that you can pull into your projects to perform common tasks.

This collection of code is known as the Python Standard Library, and it's organized into files called modules.

What is a Module?

A module is simply a Python file (.py) containing functions, classes, and variables that you can use in your own programs. Think of them as toolkits. If you need to perform mathematical calculations, you can import the math toolkit. If you need to work with dates and times, you can import the datetime toolkit.

Using modules allows you to:

  • Keep your code organized: You can split a large project into multiple smaller, more manageable files.

  • Reuse code: Write a function once in a module and import it wherever you need it.

  • Use powerful features: Access expertly-written code from the standard library without having to reinvent the wheel.

How to Use a Module: The import Statement

To use a module, you must first bring it into your program using the import statement. This is almost always done at the very top of your file.

Let's start with the random module, which is great for games and simulations.

import random

# Now we can use functions from the random module using dot notation.

# Generate a random integer between 1 and 10 (inclusive)
random_number = random.randint(1, 10)
print(f"Your random number is: {random_number}")

# Pick a random item from a list
players = ["Alice", "Bob", "Charlie", "Diana"]
winner = random.choice(players)
print(f"The winner is: {winner}!")

Exploring Other Useful Modules

The standard library is huge, but here are a few more of the most common modules you'll encounter.

The math Module

The math module provides access to mathematical functions beyond basic arithmetic.

The datetime Module

This module is essential for working with dates and times.

Different Ways to Import

You don't always have to import the entire module.

Importing Specific Functions

If you only need one or two specific functions from a module, you can import them directly using the from ... import ... syntax. This lets you use the function name without the module prefix.

Using an Alias

Sometimes module names can be long, or you might want to use a shorter name. You can give a module an alias (a nickname) using the as keyword.

Summary and What's Next

You've learned how to import and use modules, which unlocks a huge range of new capabilities for your programs.

  • A module is a Python file with reusable code.

  • The Python Standard Library is a collection of modules included with Python.

  • Use import module_name to bring a module's code into your program.

  • Access functions and variables in the module using module_name.function_name.

  • You can import specific parts of a module using from module_name import function_name.

  • You can give a module a nickname using import module_name as alias.

The standard library is amazing, but the Python community has created hundreds of thousands of other packages for specialized tasks. In the next chapter, we'll look at how to install and use these third-party packages using pip, Python's package manager.

Practice Time!

  1. Write a program that asks the user for the radius of a circle.

  2. Import the math module and use math.pi and the formula area = π * r² to calculate the area of the circle.

  3. Print the calculated area for the user.

Last updated