Modules and Random Numbers¶
By the end of this lesson you'll be able to:
- Import a module using
import,from...import, andimport...assyntax - Generate random integers with
random.randint()and random floats withrandom.random() - Pick random items with
random.choice()and shuffle a list withrandom.shuffle() - Use
random.seed()to make your random results repeatable
Python comes with a huge library of extra tools called modules.
Instead of writing everything from scratch, you import the tool you need.
The random module is one of the most fun — it lets you add surprise and variety to your programs.
Welcome to Chapter 17!
Modules are like power-ups for your programs! Import one and suddenly you can do
things Python couldn't do on its own. Today we're unlocking the random module —
perfect for games and generative art. Let's code it together!
The import Statement¶
Python's standard library contains dozens of modules ready to use.
To load a module, write import module_name at the top of your program.
After importing, access its functions with module.function().
1 2 | |
from...import — Grab Specific Names¶
If you only need one or two functions from a module, you can import just those names.
After a from...import, you call the function directly without the module prefix.
1 2 3 4 | |
import...as — Give a Module a Nickname¶
Long module names can be shortened with as:
1 2 | |
from...import * — Import Everything¶
from random import * imports every public name from the module.
This is convenient but can cause confusion if two modules define a function with the same name.
Use it only for quick experiments, not in serious programs.
The random Module¶
The random module generates numbers that look unpredictable.
Before we try each function, here's a summary of the key ones:
| Function | Returns | Example |
|---|---|---|
randint(a, b) |
Random integer from a to b (inclusive) | randint(1, 6) → 4 |
random() |
Random float from 0.0 to 1.0 | random() → 0.73... |
choice(seq) |
One random item from a list | choice(["red","blue"]) |
shuffle(lst) |
Shuffles a list in place (returns None) | shuffle(cards) |
sample(seq, k) |
List of k unique random items | sample(range(1,50), 6) |
seed(n) |
Sets the random starting point | seed(42) → same results every time |
random.randint() — Random Integers¶
randint(a, b) returns a random integer where a <= result <= b.
Both endpoints are included.
What Do You Think Will Happen?
The code below simulates rolling a 6-sided die five times.
Will you ever get the same number twice in a row? Make your guess — then run it!
Run it a few times — the results change each time because the numbers are random.
See It: Randomness Has a Shape¶
Five rolls look like pure chaos. But what happens after a thousand rolls? Before you click anything in the histogram below, predict: after 1000 rolls of one die, will some faces come up way more than others, or will the bars be roughly even?
Explore the Dice Roll Histogram MicroSim
Now switch the dropdown to Sum of two dice and roll 1000 again. The flat skyline turns into a mountain with its peak at 7 — can you figure out why there are more ways to roll a 7 than a 2? That discovery is the seed of probability.
random.choice() — Pick from a List¶
choice(seq) picks one random item from a sequence (list, string, or tuple).
random.shuffle() — Shuffle a List¶
shuffle(lst) rearranges the items of a list in a random order.
It modifies the list in place and returns None — so don't write lst = shuffle(lst).
random.random() — Random Float¶
random() returns a float between 0.0 and 1.0. The result can be exactly 0.0 but is never exactly 1.0.
This is useful when you want a percentage or probability. Multiply to scale it:
1 2 3 | |
random.sample() — Pick Without Replacement¶
sample(seq, k) picks k unique items from the sequence (no repeats).
This is like drawing lottery numbers — once a number is drawn, it can't be drawn again.
1 2 3 | |
random.seed() — Repeatable Randomness¶
Every time you run a random program, Python uses a different starting point (called a seed) so the results are different.
If you call random.seed(n) with the same number every time, you get exactly the same "random" sequence.
This is useful for testing — you want your program to behave the same way during testing.
Random Art with Turtle¶
Let's put random to work with turtle graphics — random colors, sizes, and positions to create generative art.
Run it multiple times — because of randomness, you'll get a different artwork every single time!
Creating Your Own Module¶
So far you've only used modules that already exist. You can also author your own — package a set of functions into a .py file so other programs (or your future self) can import them, exactly like random.
This Needs a Real Python Environment
Creating a separate file and importing it only works with a real Python installation — Thonny, VS Code, or the terminal. Skulpt runs a single file, so this walkthrough uses regular code blocks instead of an interactive lab.
Save the functions below in a file named fibo.py:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
Then, in a different file saved in the same folder, import it by its filename (without the .py):
1 2 3 4 5 | |
You can also grab one function directly, just like you did with random:
1 2 3 | |
Python treats every .py file the same way — whether it ships with the standard library or you wrote it five minutes ago.
Learning Check¶
Your Turn — Fix the Shuffle
The code below tries to shuffle a list and print it, but it has a bug —
it assigns the return value of shuffle() to cards, losing the list!
Fix it so the list is actually shuffled and printed.
Experiments¶
Try these changes. Predict what will happen first, then run it to check!
-
Simulate flipping a coin 10 times. Use
random.choice(["heads", "tails"])and count how many heads you get. You'll know it worked when you see a count between 0 and 10. -
Pick 6 lottery numbers from 1–49 using
random.sample(range(1, 50), 6). Print them sorted. You'll know it worked when you see 6 unique numbers in order. -
Change the random art loop count from
40to100. Notice the effect. You'll know it worked when the canvas is much more filled with shapes. -
Set
random.seed(7)before the random art loop. Run it twice. You'll know it worked when both runs produce identical artwork. -
Use
random.random()to simulate a 30% chance event: print"Lucky!"if the result is below0.3. Run it 10 times with a loop. You'll know it worked when roughly 3 out of 10 iterations print "Lucky!".
Random Wizard!
You've unlocked modules and mastered the random module!
Games, simulations, and generative art all rely on randomness — and now you can use it too.
Next chapter we'll add math power to your turtle programs. Let's keep coding!