Creating Your Own Module
Exit

Creating Your Own Module

Split code into two files and import between them

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Any .py file is a module

You don't need special syntax to create a module. Save functions in a .py file, and other files can import them. The filename (minus .py) becomes the module name.

If you create greetings.py:

def say_hello(name):
    return f"Hello, {name}!"

Any file in the same directory can import it:

from greetings import say_hello

print(say_hello("Alice"))  # Hello, Alice!

Python finds greetings.py because it searches the current directory first.

Organizing with purpose

A good module groups related functions. Put math functions in math_utils.py, string functions in text_helpers.py, file operations in file_io.py. Each module has one clear responsibility.

The name of the file should tell a reader what kind of functions live inside — without opening it.

Your task

You have two files open. string_utils.py is the module you will build — it contains two string manipulation functions. main.py is read-only and already imports from your module. Implement the two functions so main.py runs correctly.

Instructions

Implement two functions in string_utils.py.

  1. Define reverse_string(text). Return text[::-1] to reverse the string.
  2. Define count_vowels(text). Create a variable named count and set it to 0. Loop through each character in text.lower(). If the character is in "aeiou", add 1 to count. Return count.