Skip to content

Exercise 12 - Random Creations

random creation

What Is the Random Library?

The Random library has a set of commands that pick an unknown number or choice from a list.

To create the artwork, you will be using these commands from the Random library:

🐍 Python Script
import random #Import commands from the Random library.
random.choice(variablename) #Pick an item from a list of choices.
random.randint(start,end) #Pick a number between the start and end value.
  • Open Thonny, create a new file, save it as random.
  • Import the Turtle library. Set the screen size and speed.

1. Create a Spirograph

  • Build a script to make a spirograph, which is a pattern made from loops:
🐍 Python Script
#spirograph 
while True:
    pensize(3)
    pencolor("teal")
    circle(60) 
    forward(15) 
    right(62)

2. Import the Random Library

  • Just like the Turtle library, you must import the Random library for the commands to work:
🐍 Python Script
from turtle import * 
import random

3. Randomly Pick a Color from a List of Choices

You can create a variable that has a list of colors. A variable is a stored value that can change. The program will use the variable pickcolor to randomly pick a color from the list. Try it!

  • Above the spirograph code, create a variable with a list of colors:
🐍 Python Script
#random values
pickcolor=("orange", "plum", "teal")
#spirograph
while True:
    pensize(3)
    pencolor("orange")

Find more color names here.

  • Replace the value in the pencolor command with random.choice and the pickcolor variable name:
🐍 Python Script
#random values
pickcolor=("orange", "plum", "teal")
#spirograph
while True:
    pensize(3)
    pencolor(random.choice(pickcolor))
    circle(60)

4. Randomly Pick a Fill Color from a List of Choices

  • You are going to add stamps to the design. Create a pickfill list of colors and add code to make stamps different colors:
🐍 Python Script
#random values
pickcolor=("orange", "plum", "teal")
pickfill=("navy", "skyblue", "aqua", "violet")  
#spirograph 
while True:
    pensize(3)
    pencolor("teal")
    circle(60)
    forward(15)
    right(62)
    fillcolor(random.choice(pickfill)) 
    shape("circle")
    stamp()      

5. Randomly Pick a Number from a Range

  • You can have the program pick a number between two values. Replace the pen size value with a random number:
🐍 Python Script
#spirograph 
while True:
    pensize(random.randint(0, 6)) 
    pencolor(random.choice(pickcolor))
    circle(60)
  • Replace the circle value with a random number:
🐍 Python Script
#spirograph 
while True:
    pensize(random.randint(0, 6)) 
    pencolor(random.choice(pickcolor))
    circle(random.randint(0, 50))
  • Create Your Random Artwork