Skip to main content
Engineering LibreTexts

7.1: Module Basics

  • Page ID
    117564
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\dsum}{\displaystyle\sum\limits} \)

    \( \newcommand{\dint}{\displaystyle\int\limits} \)

    \( \newcommand{\dlim}{\displaystyle\lim\limits} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \(\newcommand{\longvect}{\overrightarrow}\)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)
    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 \(\PageIndex{1}\): Defining a module

    How many functions are defined in the area module?

    1. 6
    2. 10
    3. 49
    Answer

    b. The code has ten def statements, each of which defines a function.

    Concepts in Practice \(\PageIndex{2}\): Defining a module

    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
    Answer

    a. Many modules consist of function definitions only. The functions are intended to be called in other modules.

    Concepts in Practice \(\PageIndex{3}\): Defining a module

    What is the return value of cube(5)?

    1. 60
    2. 125
    3. 150
    Answer

    c. area.cube(5) is 6 * 5**2, which is 6 * 25, which is 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 \(\PageIndex{4}\): Importing a module

    What statement would import a module from a file named secret.py?

    1. import secret
    2. import secret.py
    3. import "secret.py"
    Answer

    a. When importing a module from another file, the suffix .py is removed.

    Concepts in Practice \(\PageIndex{5}\): Importing a module

    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)
    Answer

    b. The circle function must be called using the area variable that refers to the module.

    Concepts in Practice \(\PageIndex{6}\): Importing a module

    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
    Answer

    b. Adding the function to the area module makes the function easier to reuse in other programs.

    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.

    Interactive Code
    """Functions that convert metric and imperial units."""
    
    
     
    Answer

    """Functions that convert metric and imperial units."""

    def cel2fah(c):
    """Converts from Celsius to Fahrenheit."""
    return 9/5 * c + 32

    def fah2cel(f):
    """Converts from Fahrenheit to Celsius."""
    return 5/9 * (f - 32)

    def km2mi(km):
    """Converts from kilometers to miles."""
    return km / 1.60934

    def mi2km(mi):
    """Converts from miles to kilometers."""
    return mi * 1.60934

    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.
    Interactive Code
    """Example program that uses the conversion module."""
    
    speed_in_km = float(input("How fast were you driving? "))
    speed_in_mi = 0  # TODO
    print("Woah, that's like", round(speed_in_mi), "mph!")
    
    temp_in_c = float(input("What was the temperature? "))
    temp_in_h = 0  # TODO
    print("That's", round(temp_in_h), "degrees Fahrenheit!")
    
     
    Input

    180
    35

    Answer

    """Example program that uses the conversion module."""

    import conversion

    speed_in_km = float(input("How fast were you driving? "))
    speed_in_mi = conversion.km2mi(speed_in_km)
    print("Woah, that's like", round(speed_in_mi), "mph!")

    temp_in_c = float(input("What was the temperature? "))
    temp_in_h = conversion.cel2fah(temp_in_c)
    print("That's", round(temp_in_h), "degrees Fahrenheit!")


    This page titled 7.1: Module Basics is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.