Skip to ContentGo to accessibility pageKeyboard shortcuts menu
OpenStax Logo

Learning objectives

By the end of this section you should be able to

  • Write a module that consists only of function definitions.
  • Import the module and use the functions in a program.

Defining a module

Modules are defined by putting code in a .py file. The area module below is in a file named area.py. This module provides functions for calculating area.

Example 7.1

The area module

    """Functions to calculate the area of geometric shapes."""

    import math

    # 2D shapes

    def square(side):
        """Gets the area of a square."""
        return side**2

    def rectangle(length, width):
        """Gets the area of a rectangle."""
        return length * width

    def triangle(base, height):
        """Gets the area of a triangle."""
        return 0.5 * base * height

    def trapezoid(base1, base2, height):
        """Gets the area of a trapezoid."""
        return 0.5 * (base1 + base2) * height

    def circle(radius):
        """Gets the area of a circle."""
        return math.pi * radius**2

    def ellipse(major, minor):
        """Gets the area of an ellipse."""
        return math.pi * major * minor

    # 3D shapes

    def cube(side):
        """Gets the surface area of a cube."""
        return 6 * side**2

    def cylinder(radius, height):
        """Gets the surface area of a cylinder."""
        return 2 * math.pi * radius * (radius + height)

    def cone(radius, height):
        """Gets the surface area of a cone."""
        return math.pi * radius * (radius + math.hypot(height, radius))

    def sphere(radius):
        """Gets the surface area of a sphere."""
        return 4 * math.pi * radius**2

Concepts in Practice

Defining a module

1.
How many functions are defined in the area module?
  1. 6
  2. 10
  3. 49
2.
What would be the result of running area.py as a program?
  1. Functions would be defined and ready to be called.
  2. Nothing; the module has no statements to be run.
  3. SyntaxError
3.
What is the return value of cube(5)?
  1. 60
  2. 125
  3. 150

Importing a module

The module defined in area.py can be used in other programs. When importing the area module, the suffix .py is removed:

    import area
    
    print("Area of a basketball court:", area.rectangle(94, 50))
    print("Area of a circus ring:", area.circle(21))

The output is:

    Area of a basketball court: 4700
    Area of a circus ring: 1385.4423602330987

Checkpoint

Importing area in a Python shell

Concepts in Practice

Importing a module

4.
What statement would import a module from a file named secret.py?
  1. import secret
  2. import secret.py
  3. import "secret.py"
5.
What code would return the area of a circle with a radius of 3 meters?
  1. circle(3)
  2. area.circle(3)
  3. circle.area(3)
6.
A programmer would like to write a function that calculates the area of a hexagon. Where should the function be written?
  1. the main program
  2. the area module
  3. the secret module

Try It

Conversion module

Write a module that defines the following functions:

  1. cel2fah(c)
    Converts a temperature in Celsius to Fahrenheit.
    The formula is 9/5 * c + 32.
  2. fah2cel(f)
    Converts a temperature in Fahrenheit to Celsius.
    The formula is 5/9 * (f - 32).
  3. km2mi(km)
    Converts a distance in kilometers to miles.
    The formula is km / 1.60934.
  4. mi2km(mi)
    Converts a distance in miles to kilometers.
    The formula is mi * 1.60934.

Each function should include a docstring as the first line. A docstring for the module has been provided for you.

The module should not do anything except define functions. When you click the "Run" button, the module should run without error. No output should be displayed.

Try It

European vacation

Write a program that uses the conversion module from the previous exercise to complete a short story. The program's output should match the following example (input in bold):

    How fast were you driving? 180
    Woah, that's like 112 mph!
    What was the temperature? 35
    That's 95 degrees Fahrenheit!

Notice this exercise requires two files:

  1. european.py, the main program. Input and output statements are provided as a starting point. Edit the lines with TODO comments to use the conversion module.
  2. conversion.py, the other module. Copy and paste your code from the previous exercise. Import this module in european.py after the docstring.
Citation/Attribution

This book may not be used in the training of large language models or otherwise be ingested into large language models or generative AI offerings without OpenStax's permission.

Want to cite, share, or modify this book? This book uses the Creative Commons Attribution License and you must attribute OpenStax.

Attribution information
  • If you are redistributing all or part of this book in a print format, then you must include on every physical page the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
  • If you are redistributing all or part of this book in a digital format, then you must include on every digital page view the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
Citation information

© Jul 30, 2024 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution License . The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.

This book utilizes the OpenStax Python Code Runner. The code runner is developed by Wiley and is All Rights Reserved.