Creating Modules (.py files to import), online

Six activities your students do on their own devices. See who's finished, and their scores.

Creating Modules (.py files to import) in one minute

What students need to know

After import helpers, access its functions with helpers.function_name(). 'from module import name' lets you use the name directly without the module prefix.

Any .py file is a module — import it to use what's inside. Modules let you split code into files and share functions across projects.

Mistakes students make

  • Don't include .py: just the module name.
  • Module names are case-sensitive. File is helpers.py, so use helpers.
  • With 'from import', use greet() directly: no module prefix.
  • With 'import helpers', must use helpers.greet() not just greet().
PREVIOUS · MODULE 47Files – Error Handling (try/except)
YOU ARE HERE · MODULE 48Creating Modules (.py files to import)
NEXT · MODULE 49OOP – Classes & Objects

Discover other journeys with this module

What students will learn in this module

Every question in Module 48

Quick questions

  1. What is a module?AA folderBA .py file with functions you can import
  2. If you create helpers.py, how do you import it?Aimport helpersBimport helpers.py
  3. from math import sqrt what does this do?AImports everythingBImports only the sqrt function
  4. Why create your own modules?ATo organize and reuse codeBPython requires it
  5. Where must your module file be?AIn the same folder (or Python's path)BIn a special folder only

Key terms

Students type the meaning of:

  • Module
  • import module
  • from module import func
  • __name__

Match the pairs

import my moduleMatch it to what it does
from helpers import
greet()
Match it to what it does
import helpers
helpers.greet()
Match it to what it does
from helpers import greet
greet()
Match it to what it does
# In helpers.py:
def greet():
    print('Hi')
Match it to what it does
# In main.py:
import helpers
helpers.greet()
Match it to what it does

Fill in the blanks

  1. ______ helpers
    print(helpers.greet('Al'))
  2. ____ helpers import greet
    print(greet('Al'))
  3. import helpers
    print(helpers._____('Alice'))
  4. if ________ == '__main__':
        print('Running directly')
  5. from helpers import ___
    result = add(3, 5)

Spot the error

Question 1

A# Import our helpers moduleBimport helpers.pyChelpers.greet('Alice')Dprint('Done')

Question 2

Aimport HelpersBresult = Helpers.greet('Al')Cprint(result)Dprint('Done')

Question 3

Afrom helpers import greetBresult = helpers.greet('Al')Cprint(result)Dprint('Done')

Question 4

Aimport helpersBresult = greet('Al')Cprint(result)Dprint('Done')

Question 5

Afrom helpers import *B# imports everythingCgreet('Alice')D# recommended approach?