Skip to ContentGo to accessibility page

7.3 Top-level code

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

Concepts in Practice

Side effects

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

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

Concepts in Practice

Using __name__

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__
    
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__
    
6.
What line is useful for preventing side effects when importing?
  1. if __name__ == "main":
  2. if __name__ == __main__:
  3. if __name__ == "__main__":

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.

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
Citation/Attribution
Reuse and redistribution of this content in digital or print format:
  • 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 prior written permission.
  • This book uses the Creative Commons Attribution-NonCommercial-ShareAlike License, which means that you can reuse and modify the material only for noncommercial purposes, must attribute OpenStax, and must distribute any derivative works under the same license.
  • Any commercial printing of this textbook, including using a local or custom printer, must be approved by OpenStax, and proper citation provided.
  • OpenStax-copyrighted images, activities, assessments, and similar components of this book are subject to the same licensing – CC-BY-NC-SA. They can be used for noncommercial purposes with attribution. Commercial use requires permission.
  • Permission requests: Anyone who intends to incorporate this content (including text, images, and other components) into large language models, use it in AI offerings, use it commercially (including in print), and/or has questions about another use case is welcome to complete our reuse request form.
Attribution information
  • If you are redistributing all or part of this book in a noncommercial 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 noncommercial digital format, then for every page that includes OpenStax content, you must license the derivative work under the same CC-BY-NC-SA license as the original, and 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

The information below includes the information needed to generate citations in most major styles (APA, MLA, etc.); you must reformat and organize the information as needed to fit the requirements of the style. Use the information below to generate a citation. We recommend using a citation tool such as this one.

© Apr 23, 2026 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike License. The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo, and Rice University name, and Rice University logo trademarks, or wordmarks 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.