Custom modules help you organize your code into separate files. This makes your programs easier to read and reuse.
Creating custom modules in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
Create a file named mymodule.py: def greet(name): return f"Hello, {name}!" In another file, import and use it: import mymodule print(mymodule.greet("Alice"))
The module file must have a .py extension.
Use import module_name to use the module in another file.
Examples
Python
# mymodule.py def add(a, b): return a + b # main.py import mymodule print(mymodule.add(3, 4))
area function from the module.Python
# mymodule.py PI = 3.14 def area(radius): return PI * radius * radius # main.py from mymodule import area print(area(5))
Python
# mymodule.py class Person: def __init__(self, name): self.name = name def greet(self): return f"Hi, I am {self.name}." # main.py from mymodule import Person p = Person("Bob") print(p.greet())
Sample Program
This program creates a module with a multiply function. The main program imports it and prints the result.
Python
# file: mymodule.py def multiply(x, y): return x * y # file: main.py import mymodule result = mymodule.multiply(6, 7) print(f"6 times 7 is {result}")
Important Notes
Make sure the module file is in the same folder as your main program or in Python's search path.
You can import multiple functions or classes using commas: from module import func1, func2.
Use as to rename modules or functions when importing for easier use.
Summary
Custom modules help organize and reuse code.
Create a module by saving functions or classes in a .py file.
Import modules using import or from ... import to use their code.
Practice
1. What is the main purpose of creating a custom module in Python?
easy
Solution
Step 1: Understand what a module is
A module is a file containing Python code like functions or classes.Step 2: Identify the purpose of custom modules
Custom modules help organize code and allow reuse in different programs.Final Answer:
To organize and reuse code easily -> Option DQuick Check:
Custom modules = organize and reuse code [OK]
Hint: Modules group code for reuse and clarity [OK]
Common Mistakes:
- Thinking modules speed up code execution
- Confusing modules with data storage
- Assuming modules create user interfaces
2. Which of the following is the correct way to import a custom module named
mymodule?easy
Solution
Step 1: Recall Python import syntax
Python uses the keywordimportto bring in modules.Step 2: Match correct syntax
Onlyimport mymoduleis valid Python syntax for importing a module.Final Answer:
import mymodule -> Option AQuick Check:
Import module = import keyword [OK]
Hint: Use 'import' keyword to bring in modules [OK]
Common Mistakes:
- Using 'include' or 'load' which are not Python keywords
- Trying 'using' which is from other languages
- Misspelling 'import'
3. Given a file
What will be the output of this code?
math_ops.py with this code:def add(a, b):
return a + b
What will be the output of this code?
import math_ops print(math_ops.add(3, 4))
medium
Solution
Step 1: Understand the function in math_ops.py
The functionaddtakes two numbers and returns their sum.Step 2: Analyze the import and function call
Importingmath_opsallows callingmath_ops.add(3, 4), which returns 3 + 4 = 7.Final Answer:
7 -> Option AQuick Check:
3 + 4 = 7 [OK]
Hint: Imported functions run normally with correct arguments [OK]
Common Mistakes:
- Confusing string concatenation with addition
- Expecting errors due to import
- Forgetting to call function with parentheses
4. You have a module file named
utils.py with a function greet(). Which of these import statements will cause an error?medium
Solution
Step 1: Understand Python import rules
You can import a module or specific functions from it, but not a function as a submodule.Step 2: Check each option
Options B, C, and D are valid. import utils.greet tries to import a function as a module, which causes ImportError.Final Answer:
import utils.greet -> Option BQuick Check:
Functions are imported, not as submodules [OK]
Hint: Import modules or functions, not functions as modules [OK]
Common Mistakes:
- Trying to import a function like a module
- Confusing 'from' and 'import' usage
- Using invalid aliases
5. You want to create a custom module
text_utils.py with a function count_vowels(text) that returns the number of vowels in a string. Which code correctly defines this function?hard
Solution
Step 1: Check vowel counting logic
def count_vowels(text): vowels = 'aeiouAEIOU' return sum(1 for char in text if char in vowels) uses a string with both uppercase and lowercase vowels and counts characters in one line using sum and generator.Step 2: Compare other options
def count_vowels(text): vowels = ['a', 'e', 'i', 'o', 'u'] count = 0 for char in text: if char in vowels: count += 1 return count misses uppercase vowels, def count_vowels(text): vowels = 'aeiou' count = 0 for char in text: if char in vowels: count += 1 return count misses uppercase vowels, def count_vowels(text): vowels = 'AEIOU' count = 0 for char in text: if char.lower() in vowels: count += 1 return count incorrectly checks lowercase char in uppercase vowels string.Final Answer:
def count_vowels(text): vowels = 'aeiouAEIOU' return sum(1 for char in text if char in vowels) -> Option CQuick Check:
Count vowels with case check = def count_vowels(text): vowels = 'aeiouAEIOU' return sum(1 for char in text if char in vowels) [OK]
Hint: Use sum with generator and full vowel set for case [OK]
Common Mistakes:
- Ignoring uppercase vowels
- Checking lowercase char in uppercase vowels string
- Using list instead of string for vowels unnecessarily
