Learning LibraryCore Coding LibraryKids

Importing: borrow tools Python already has

You don't have to build everything yourself. Python ships with toolboxes full of ready-made commands. One line borrows a toolbox so your program can use it.

The big idea

import borrows a toolbox of ready-made code, called a module. After that, you reach its tools with the module's name and a dot.

See it in code

1Start simple

The import line goes at the very top. Then random.choice(...) means "the choice tool, from the random toolbox." It picks one item from a list:

python
import random

specials = ["croissants", "maple scones", "cupcakes"]
special = random.choice(specials)
print("Today's special:", special)
One run of this program printed:
Today's special: maple scones

Run it again and you may get a different special. The computer picks, and you don't know which one is coming.

2A step further

One import unlocks the whole toolbox. random.randint(1, 3) is a second tool from the same module. It picks a whole number from 1 to 3:

python
import random

specials = ["croissants", "maple scones", "cupcakes"]
special = random.choice(specials)
discount = random.randint(1, 3)
print(f"Today's special: {special}, ${discount} off!")
Two tools, one import:
Today's special: maple scones, $1 off!

You imported once and used the toolbox twice. The dot is how you say which toolbox a tool lives in.

3In the bakery

Borrowed tools work anywhere your own code does, even inside a loop. Here the picker runs once for every day of the week:

python
import random

specials = ["croissants", "maple scones", "cupcakes"]
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]

print("=== THIS WEEK'S SPECIALS ===")
for day in days:
    print(f"{day}: {random.choice(specials)}")
One run of the week's plan:
=== THIS WEEK'S SPECIALS ===
Monday: maple scones
Tuesday: croissants
Wednesday: maple scones
Thursday: cupcakes
Friday: croissants

The pick happens inside the loop, so each day gets a fresh one. Five trips, five picks.

The same idea, everywhere

The paint studio and the arcade do their importing for you. Commands like circle and pick are borrowed before your first line runs, so they are simply there.

Try it yourself

Add a fourth special to the list and run the week plan a few times. Then try random.randint(1, 6) on its own line with a print. You just made a dice roll.

The common mistake

Using a tool before importing it. Leave out import random and the first random.choice stops with a NameError: Python has never heard of random. Imports go at the top.

What it unlocks

The random toolbox has more to offer, and randomness gets its own article. Tools you borrow are functions, just like the recipes you write yourself.

Older, or want more depth? Read the Teens version →