Guide Python Beginner

19.1 Modules and Imports

Organize scripts into reusable files.

2 min read

Before you start

Work through the earlier fundamentals chapters. Use a Python 3 interpreter and run each example locally.

Core concepts

A Python file can be imported as a module. Imported top-level code executes on first import in a process, so keep network calls and CLI parsing out of module scope. The if __name__ == "__main__" guard runs an entry point only when the file is executed directly.

Group related modules in a package, commonly using an __init__.py file. Prefer clear imports and avoid names such as csv.py or logging.py that shadow standard-library modules. Use a project virtual environment for third-party dependencies.

Worked example

# Save as health.py
def is_healthy(status):
    return status == "healthy"

def main():
    print(is_healthy("healthy"))

if __name__ == "__main__":
    main()

Mini lab

Save the example as health.py. In another file, import is_healthy and assert that critical returns False. Importing the module must not print anything.

HintStart with the smallest input. Print intermediate values while exploring, then replace those prints with checks of the expected result.
Show a solution
# Save beside health.py as check_health.py
from health import is_healthy

assert is_healthy("critical") is False
print("check passed")

Knowledge check

What does the main guard prevent?

Check your answerIt prevents the guarded entry-point code from running when another module imports the file.

Common mistake

Circular imports often indicate responsibilities are mixed. Move shared definitions to a small independent module.

Completion checklist

  • Run the example and explain its output.
  • Complete the mini lab without copying the solution.
  • Test an edge case and explain how the code handles it.
  • Answer the knowledge check in your own words.

Fundamentals overview · Continue →

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form