Modules (deeper)
๐ฆ๐ Technique Card: Importing and Using Modules in Python (deeper)
๐ What Youโll Explore
Learn how to import a sack full of ready-made code (called a module) so you can use cool tools like picking a random item from a list.
๐ Whatโs a Module?
A module is like a sack of code.
Imagine a sack filled with helpful tools that someone else made for you โ tools that help your program do smart things without you having to build them from scratch.
One sack might help with maths.
Another might help with telling the time.
And one fun sack is called random
โ itโs full of tools for picking things randomly!
๐ฏ Why Use a Sack (Module)?
- It saves time.
- It gives your program superpowers!
- You donโt have to build everything yourself.
๐ช How Do I Open a Sack?
You use the import command:
import random
This means:
๐ฃ๏ธ โHey Python, bring me the sack called random
!โ
Now you can use anything inside the sack.
๐งบ How to Grab a Tool from the Sack
Letโs say we want to pick a random name from a list:
name = random.choice(["Ava", "Ziggy", "Sky"])
Hereโs whatโs happening:
random
= the sackchoice
= a tool inside the sack- The dot (
.
) joins them:random.choice
๐ก You can think of the dot like a possessive apostrophe:
โThe
choice
that belongs torandom
โ
Just like:
โZiggyโs hatโ = the hat that belongs to Ziggy
random.choice()
= the choice tool that belongs to the random sack
๐ ๏ธ Whatโs Inside These Sacks?
Each sack (module) contains code: clever instructions written by other programmers.
We donโt need to know exactly how that code works to use it โ just like we can use a calculator without knowing how all the buttons are wired inside.
๐ช Can We Import Just One Tool?
Yes! But itโs a bit like pulling just one thing out of the sack and leaving the rest behind:
from random import choice
Now you can write:
name = choice(["Storm", "Flame", "Frost"])
That works, but sometimes itโs nicer to keep using the sack so we know where the tool came from. It is more clear when we have lots of code - if we have choice()
it is not so clear but if we use random.choice()
it is more clear that the choice()
code came from the random
module (sack!)
๐ง Quick Recap
- A module is like a sack full of code.
- We use
import
to bring the sack into our project. - We use the dot (
.
) to take tools out of the sack. random.choice()
means: โUse the choice tool from the random sack!โ
๐ Other Useful and Related Cards
- ๐ Technique Card: Lists in Python (practical)
- ๐ Technique Card: Getting a Random Choice from a List in Python (practical)