Skip to content

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 sack
  • choice = 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 to randomโ€

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!โ€