Bird
Raised Fist0
Pythonprogramming~10 mins

Creating custom modules in Python - Visual Walkthrough

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Creating custom modules
Write functions/classes in a .py file
Save file as module_name.py
In another file, use import statement
Call functions or use classes from module
Program runs using custom module code
You write code in a file, save it as a module, then import and use it in another file.
Execution Sample
Python
def greet(name):
    return f"Hello, {name}!"

# In another file:
import mymodule
print(mymodule.greet("Alice"))
Defines a greet function in a module and uses it from another file to print a greeting.
Execution Table
StepActionCode LineResult/Output
1Define function greet in mymodule.pydef greet(name): ...Function greet created
2Save file as mymodule.pyFile savedModule ready to import
3Import mymodule in main.pyimport mymoduleModule loaded
4Call greet with 'Alice'mymodule.greet("Alice")Returns 'Hello, Alice!'
5Print the returned greetingprint(mymodule.greet("Alice"))Output: Hello, Alice!
💡 Program ends after printing the greeting
Variable Tracker
VariableStartAfter greet('Alice')Final
nameundefined"Alice"undefined after function ends
return valueundefined"Hello, Alice!""Hello, Alice!"
Key Moments - 3 Insights
Why do we save the code in a separate .py file?
Because the module must be a separate file to import it, as shown in execution_table step 2.
What happens when we import the module?
Python loads the module file so we can use its functions, as seen in step 3.
Why do we use the module name before the function call?
To tell Python which module the function comes from, shown in step 4 calling mymodule.greet.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 5?
AHello, Alice!
Bgreet
Cmymodule
DAlice
💡 Hint
Check the 'Result/Output' column in step 5 of the execution_table.
At which step is the module file saved?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look for the action mentioning saving the file in the execution_table.
If we forget to import the module, what will happen when calling greet?
AThe program prints the greeting anyway
BPython raises an error because greet is undefined
CThe program runs but prints nothing
DThe module imports automatically
💡 Hint
Think about what happens if you call a function without importing its module, related to step 3 and 4.
Concept Snapshot
Create a Python module by saving functions/classes in a .py file.
Import the module in another file using 'import module_name'.
Call functions with 'module_name.function()'.
This helps organize code and reuse it easily.
Full Transcript
Creating custom modules in Python means writing functions or classes in a separate .py file and saving it. This file becomes a module. In another Python file, you import this module using the import statement. Then you can call the functions or use classes from the module by prefixing them with the module name. For example, if you have a greet function in mymodule.py, you import mymodule and call mymodule.greet('Alice'). The program runs by loading the module and executing the function, printing the greeting. This method helps keep code organized and reusable.

Practice

(1/5)
1. What is the main purpose of creating a custom module in Python?
easy
A. To make the program run faster
B. To store data permanently
C. To create graphical user interfaces
D. To organize and reuse code easily

Solution

  1. Step 1: Understand what a module is

    A module is a file containing Python code like functions or classes.
  2. Step 2: Identify the purpose of custom modules

    Custom modules help organize code and allow reuse in different programs.
  3. Final Answer:

    To organize and reuse code easily -> Option D
  4. Quick 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
A. import mymodule
B. include mymodule
C. using mymodule
D. load mymodule

Solution

  1. Step 1: Recall Python import syntax

    Python uses the keyword import to bring in modules.
  2. Step 2: Match correct syntax

    Only import mymodule is valid Python syntax for importing a module.
  3. Final Answer:

    import mymodule -> Option A
  4. Quick 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 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
A. 7
B. 34
C. TypeError
D. NameError

Solution

  1. Step 1: Understand the function in math_ops.py

    The function add takes two numbers and returns their sum.
  2. Step 2: Analyze the import and function call

    Importing math_ops allows calling math_ops.add(3, 4), which returns 3 + 4 = 7.
  3. Final Answer:

    7 -> Option A
  4. Quick 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
A. import utils
B. import utils.greet
C. from utils import greet
D. from utils import greet as hello

Solution

  1. Step 1: Understand Python import rules

    You can import a module or specific functions from it, but not a function as a submodule.
  2. 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.
  3. Final Answer:

    import utils.greet -> Option B
  4. Quick 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
A. def count_vowels(text): vowels = 'aeiou' count = 0 for char in text: if char in vowels: count += 1 return count
B. def count_vowels(text): vowels = ['a', 'e', 'i', 'o', 'u'] count = 0 for char in text: if char in vowels: count += 1 return count
C. def count_vowels(text): vowels = 'aeiouAEIOU' return sum(1 for char in text if char in vowels)
D. def count_vowels(text): vowels = 'AEIOU' count = 0 for char in text: if char.lower() in vowels: count += 1 return count

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    def count_vowels(text): vowels = 'aeiouAEIOU' return sum(1 for char in text if char in vowels) -> Option C
  4. Quick 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