Using Built-in and Custom Modules

Tutorial 4 of 5

Introduction

Goal

This tutorial aims to guide you through using both built-in and custom Python modules. We will take a deep dive into how to import and use these modules, as well as how to create your own.

Learning Outcomes

By the end of this tutorial, you will be able to:
1. Understand what a module is and its purpose
2. Import and use built-in Python modules
3. Create, import and use your own custom Python modules

Prerequisites

To follow this tutorial, you should have a basic understanding of Python syntax and programming concepts. Knowledge of functions would also be beneficial.

Step-by-Step Guide

What is a Module?

In Python, a module is a file containing Python definitions and statements. It helps in organizing related code into a single file, which can be easily managed. Python has several built-in modules that you can use as is, and also allows you to create your own modules.

Using Built-in Modules

To use a built-in module, you need to import it using the import statement. Here is an example of importing and using the built-in math module:

import math

# Now we can use the math module's functions
print(math.sqrt(16))  # prints: 4.0

Creating and Using Custom Modules

Creating your own module is as simple as creating a Python file. Let's create a module named mymodule.py:

# mymodule.py
def greet(name):
    print(f"Hello, {name}!")

To use the greet function from mymodule.py, you can import it into another Python file:

# main.py
import mymodule

mymodule.greet("Alice")  # prints: Hello, Alice!

Code Examples

Example 1: Using the random module

import random

# Generate a random number between 1 and 10
random_number = random.randint(1, 10)
print(random_number)

# This will print a random number between 1 and 10

Example 2: Creating and using a custom module

# mymodule.py
def multiply(x, y):
    return x * y
# main.py
import mymodule

result = mymodule.multiply(7, 8)
print(result)  # prints: 56

Summary

In this tutorial, we learned about Python modules, how to import and use built-in modules, and how to create and use custom modules. The next step is to practice these concepts until you're comfortable with them. You could also explore more built-in Python modules and their functionalities.

Practice Exercises

  1. Use the datetime module to print the current date and time.
  2. Create a custom module that contains a function to calculate the area of a rectangle. Use this module in a different Python file.
  3. Create a custom module with several different functions, and then import only one of those functions into another Python file.

Solutions

import datetime

print(datetime.datetime.now())
# rectangle.py
def area(length, width):
    return length * width
# main.py
import rectangle

print(rectangle.area(5, 10))  # prints: 50
# mymodule.py
def func1():
    pass

def func2():
    pass

def func3():
    pass
# main.py
from mymodule import func2

func2()