Modules and environments
Create and import your own module
Put a reusable function in a separate Python file.
Lesson 40 of 63
Reading: about 2 min
Lesson + practice: about 15 min
Difficulty: Intermediate
On this page5 sections
Save a function in study_math.py and import it from a second file in the same directory. Create both files in your editor: study_math.py holds the function, and main.py imports and uses it. Run python main.py from that folder. A module executes its top-level statements once when first imported in a process.
Worked example
def total(values):
return sum(values)import study_math
print(study_math.total([20, 25]))45
Why this works
The import searches the script directory and other entries on sys.path. Keeping definitions in a module lets multiple scripts reuse them.
Another case
def greet(name):
return f"Hi, {name}"import greetings
print(greetings.greet("Sam"))Hi, Sam
Practice
Add an average(values) function to study_math.py and call it from main.py. Decide what should happen for an empty list.
Check the practice result
Reveal answer
For nonempty values, sum(values) / len(values) works. Handle an empty list explicitly, such as raising ValueError.
Try another case
You save a script as random.py, and another script in the same folder runs import random. What goes wrong?
Check your answer
Reveal answer
Python imports your random.py instead of the standard-library module, so functions such as random.randint are missing. Rename your file.
Your progress
Reveal the check answer or reach the end to complete this lesson.