By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
Creating your own modules in Python involves writing .py files and using the name == 'main' construct. This is crucial for organizing code, making it reusable, and maintaining clean, modular projects. In real-world applications, poor module management can lead to code that is difficult to maintain and debug. For exam candidates, this topic is often tested for its foundational role in Python programming. Misunderstanding it can result in inefficient code and failed exam questions.
my_module.py
Common Pitfall: Naming the file with spaces or special characters can cause issues.
Define Functions and Classes
python def greet(name): return f"Hello, {name}!"
Common Pitfall: Forgetting to define functions can lead to errors when importing.
Use name == 'main'
python if __name__ == '__main__': print(greet("World"))
greet
Common Pitfall: Omitting this can cause unwanted code execution during imports.
Import the Module
python import my_module print(my_module.greet("Alice"))
Common Pitfall: Incorrect import paths can lead to ModuleNotFoundError.
Use from ... import ...
python from my_module import greet print(greet("Bob"))
Experts view modules as building blocks of a larger system. They focus on creating self-contained, reusable components that can be easily integrated and tested. Instead of writing monolithic scripts, they think in terms of modular, maintainable code.
__name__ == '__main__'
Exam trap: Questions may test for unintended code execution.
The mistake: Using incorrect import paths.
Exam trap: Path-related questions are common.
The mistake: Naming conflicts due to poor namespace management.
Exam trap: Questions on namespace conflicts.
The mistake: Overusing from ... import ....
from ... import ...
Scenario: You are developing a Python project with multiple modules. You need to create a module for mathematical operations and use it in your main script. Question: Write the code for the mathematical module and the main script. Solution:1. Create a file named math_ops.py: ```python def add(a, b): return a + b
math_ops.py
def subtract(a, b): return a - b
if name == 'main': print(add(5, 3)) 2. Create a file named `main.py`:python from math_ops import add, subtract
2. Create a file named `main.py`:
print(add(10, 5)) print(subtract(10, 5)) Answer: The main script will output: 15 5 `` Why it works: Themath_opsmodule defines reusable functions and usesname == 'main'` to control execution. The main script imports and uses these functions correctly.
Answer: The main script will output:
`` Why it works: The
module defines reusable functions and uses
import module_name
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.