Lesson 20 of 30

Lesson 20 ? Import your own helper

Title: Split code into small files

Description: Create a helper file and import functions from it.

Why it matters for kids: Bigger projects are easier when each file has a simple job.


1. Create helpers.py

pythonpython
def say_good_morning(name):
    print(f"Good morning, {name}!")

2. Use the helper

Create main.py in the same folder:

pythonpython
from helpers import say_good_morning

say_good_morning("Mia")
say_good_morning("Leo")

Run:

bashbash
python main.py

3. Add a math helper

In helpers.py:

pythonpython
def double(number):
    return number * 2

In main.py:

pythonpython
from helpers import double

print(double(5))
print(double(12))

4. Import more than one function

pythonpython
from helpers import double, say_good_morning

say_good_morning("Sam")
print(double(8))

5. Easy examples

pythonpython
# helpers.py
def make_robot_name(color):
    return f"{color} Bot"
pythonpython
# main.py
from helpers import make_robot_name

print(make_robot_name("Blue"))
pythonpython
# helpers.py
def add_stars(word):
    return f"*** {word} ***"

6. Mini challenge

Click each example to open it.

Example 1

Create helpers.py.

Example 2

Add a hello function to helpers.

Example 3

Create main.py.

Example 4

Import one helper function.

Example 5

Call the helper function.

Example 6

Add a double function.

Example 7

Import the double function.

Example 8

Print double(5).

Example 9

Add a robot name helper.

Example 10

Create and import triple.