Module 07 · Lesson 03
Modules and Packages
Reuse code across files: import modules from the standard library and your own project, choose between import styles, and guard a script's main code with __name__.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Three ways to import
- Look inside a module
- The main guard
- Watch names arrive
Code from other files
A module is a Python file full of ready-made tools. `import` lets you use them.
import
import mathloads the module. Reach its tools with a dot:math.sqrt(16).from ... import
from math import pibrings in one name, so you can writepion its own.as
import statistics as statsgives a long name a short nickname.Your own
Any
.pyfile you write is a module. A folder of them is a package.
Modules everywhere
Python ships with hundreds of modules, and other people have written many more.
- Games
randomrolls dice and shuffles cards. - Big appsLarge programs split their code into packages such as
shop.cartandshop.payments. - Dates and times
datetimeknows today's date and how long until the weekend. - Your helpersWrite a helper once in
helpers.py, then import it wherever you need it.
An import with a nickname
This line takes one function out of a module. Tap each part to see its job.
Part 1 of 6
from:Names the module to take something out of.
Use ready-made modules
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6import
import loads a module. A dot reaches the tools inside it.
Your turn: Print math.pow(2, 10) and compare it with 2 ** 10.
import math print(math.sqrt(81)) print(math.pi) print(math.floor(7.9), math.ceil(7.1))
Press Run to see what it prints.Watch names arrive
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- import math
- from statistics import mean as average
- sides = [3, 4]
- long_side = math.sqrt(sides[0] ** 2 + sides[1] ** 2)
- avg = average(sides)
- print("long side", long_side)
- print("average", avg)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.Rounding a negative down:
import math
print(math.floor(-7.2))0 of 6 answered
Common module misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
import math # math.sqrt(9)
from math import sqrt, pi # sqrt(9)
import statistics as st # st.mean([1, 2])
from payments import cards # module inside a package
from payments.cards import charge
if __name__ == "__main__": # only when run directly
main()
dir(math) # names a module offersPress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
Summarising test scores with statistics
Report the mean, median and highest score of a class without writing the maths yourself.
import statistics
scores = [72, 85, 90, 64, 85, 78]
print("Mean:", round(statistics.mean(scores), 1))
print("Median:", statistics.median(scores))
print("Most common:", statistics.mode(scores))
print("Highest:", max(scores))Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Forgetting the module prefix
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
import math print(sqrt(16))
Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Hospitality
Splitting a bill with helper modules
A restaurant's till program uses the standard library for rounding and money maths instead of hand-written arithmetic, keeping the main program short.
Why Python fits
math.ceilrounds each share up to the next penny, so the restaurant never collects less than the bill. Importingmeanby name keeps the tip line short, whilemath.ceilkeeps its prefix because it is used only once.Pythonimport math from statistics import mean bill = 87.40 people = 3 share = math.ceil(bill / people * 100) / 100 print("Each pays:", share) print("Collected:", round(share * people, 2)) tips = [5.0, 7.5, 4.0] print("Average tip:", round(mean(tips), 2))OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Where does Python look for modules?
How do I install modules that are not in the standard library?
Which standard modules are worth knowing first?
Does a package always need __init__.py?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 8 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.