Skip to main content
Engineering LibreTexts

7.3: Top-level Code

  • Page ID
    117566
  • \( \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

    • Identify code that will run as a side effect of importing.
    • Explain the purpose of if __name__ == "__main__".

    Side effects

    Modules define functions and constants to be used in other programs. When importing a module, all code in the module is run from top to bottom. If a module is not designed carefully, unintended code might run as a side effect. The unintended code is generally at the top level, outside of function definitions.

    Checkpoint: Sphere test code
    Concepts in Practice \(\PageIndex{1}\)

    Which line would cause a side effect when imported?

    1

    import math

    2

     

    3

    print("Defining sphere function")

    4

     

    5

    def sphere(radius):

    6

    """Gets the volume of a sphere."""

    7

    return 4/3 * math.pi * radius**3
    1. line 1
    2. line 3
    3. line 5
    Answer

    b. Whenever this module is imported, Python will output "Defining sphere function" as a side effect.

    Concepts in Practice \(\PageIndex{2}\)

    The following volume.py module causes a side effect.

    import math
    
    def sphere(radius):
      """Gets the volume of a sphere."""
      return 4/3 * math.pi * radius**3
    
    for r in range(10000000):
      volume = sphere(r)
    
    1. true
    2. false
    Answer

    a. Even though nothing is printed, calling the sphere function ten million times causes a delay in the main program.

    Concepts in Practice \(\PageIndex{3}\)

    The following greeting.py module causes a side effect.

    name = input("What is your name? ")
    print(f"Nice to meet you, {name}!")
    live = input("Where do you live? ")
    print(f"{live} is a great place.")
    
    1. true
    2. false
    Answer

    a. All code is at the top level, and no functions are defined. Importing this module would run all code as a side effect.

    Using __name__

    Python modules often include the statement if __name__ == "__main__" to prevent side effects. This statement is true when the module is run as a program and false when the module is imported.

    Checkpoint: The main module
    Concepts in Practice \(\PageIndex{4}\)

    What is the output when running the following test.py module?

    import math
    
    print(math.__name__)
    print(__name__)
    
    1. >math
      test
    2. __main__
      test
      
    3. math
      __main__
    Answer

    c. The variable __name__ is the module's name, unless the module was run as the main program. In that case, __name__ is "__main__" .

    Concepts in Practice \(\PageIndex{5}\)

    What is the output when importing the following test.py module?

    import math
    
    print(math.__name__)
    print(__name__)
    
    1. math
      test
      
    2. __main__
      test
      
    3. math
      __main__
    Answer

    a. Since test.py was imported, the value of __name__ is "test" . 6.

    Concepts in Practice \(\PageIndex{6}\)

    What line is useful for preventing side effects when importing?

    1. if __name__ == "main":
    2. if __name__ == __main__:
    3. if __name__ == "__main__":
    Answer

    This line is found in many Python modules to check if the module was run as the main program.

    Exploring further

    Variables that begin and end with double underscores have special meaning in Python. Double underscores are informally called "dunder" or "magic" variables. Other examples include __doc__ (the module's docstring) and __file__ (the module's filename).

    Try It: Side effects

    This exercise is a continuation of the "Missing imports" exercise. Previously, you added missing import statements to the top of the program. Now, modify the program to prevent side effects when importing the program as a module:

    1. Add if __name__ == "__main__" at the end.
    2. Move all test code under that if statement.

    The program should run without errors and produce the same output as before.

    Interactive Code
    from math import sqrt
    from area import circle
    
    def is_prime(n):
        """Returns True if n is prime."""
        if n < 2:
            return False
        for i in range(2, int(sqrt(n)) + 1):
            if n % i == 0:
                return False
        return True
    
    # Test the is_prime function
    for n in range(10):
        if is_prime(n):
            print(n, "is prime")
        else:
            print(n, "is NOT prime")
    
    def pizza_rate(size, price):
        """Calculates the value of a pizza coupon.
    
        Args:
            size (int): Diameter of the pizza in inches.
            price (float): Advertised price of the pizza.
    
        Returns:
            float: The pizza's price per square inch.
        """
        return price / circle(size / 2)
    
    # Test the pizza_rate function
    print()
    print("  Small for $4.99:", pizza_rate(10, 4.99))
    print(" Medium for $5.99:", pizza_rate(12, 5.99))
    print("  Large for $7.99:", pizza_rate(14, 7.99))
    print("X-Large for $9.99:", pizza_rate(16, 9.99))
    
     
    Input

    Quoth the Raven:
    "Nevermore"
    3

    Answer (prime_pizza2.py)

    from math import sqrt
    from area import circle

    def is_prime(n):
    """Returns True if n is prime."""
    if n < 2:
    return False
    for i in range(2, int(sqrt(n)) + 1):
    if n % i == 0:
    return False
    return True

    def pizza_rate(size, price):
    """Calculates the value of a pizza coupon.

    Args:
    size (int): Diameter of the pizza in inches.
    price (float): Advertised price of the pizza.

    Returns:
    float: The pizza's price per square inch.
    """
    return price / circle(size / 2)

    if __name__ == "__main__":

    # Test the is_prime function
    for n in range(10):
    if is_prime(n):
    print(n, "is prime")
    else:
    print(n, "is NOT prime")

    # Test the pizza_rate function
    print()
    print(" Small for $4.99:", pizza_rate(10, 4.99))
    print(" Medium for $5.99:", pizza_rate(12, 5.99))
    print(" Large for $7.99:", pizza_rate(14, 7.99))
    print("X-Large for $9.99:", pizza_rate(16, 9.99))

    Try It: Conversion test

    This exercise is a continuation of the "Conversion module" exercise. Previously, you wrote the functions cel2fah, fah2cel, km2mi, and mi2km. Write test code at the end of conversion.py (the original file) for each of these functions. The test code must not run as a side effect when conversion is imported by other programs. When running conversion.py as the main program, the test output should be:

        0 C is 32 F
        5 C is 41 F
        10 C is 50 F
        15 C is 59 F
        20 C is 68 F
    
        20 F is -7 C
        25 F is -4 C
        30 F is -1 C
        35 F is 2 C
        40 F is 4 C
        
        1 km is 0.6 mi
        2 km is 1.2 mi
        3 km is 1.9 mi
        4 km is 2.5 mi
        5 km is 3.1 mi
        
        5 mi is 8.0 km
        6 mi is 9.7 km
        7 mi is 11.3 km
        8 mi is 12.9 km
        9 mi is 14.5 km
    Interactive Code
    """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
    
     
    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

    if __name__ == "__main__":

    for c in range(0, 21, 5):
    f = round(cel2fah(c))
    print(f"{c} C is {f} F")

    print()
    for f in range(20, 41, 5):
    c = round(fah2cel(f))
    print(f"{f} F is {c} C")

    print()
    for km in range(1, 6):
    mi = round(km2mi(km), 1)
    print(f"{km} km is {mi} mi")

    print()
    for mi in range(5, 10):
    km = round(mi2km(mi), 1)
    print(f"{mi} mi is {km} km")


    This page titled 7.3: Top-level Code 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.