Random Numbers, Tuples, and Lists
Tuples
Tuples are ordered data containers, which cannot be modified after they are assigned.
import turtle
import random
turtle.speed(9)
colors = ("Green", "Blue", "Orange", "Pink", "Red", "Purple", "Magenta", "Cyan", "Yellow", "Black")
for i in range(100):
color_index = random.randint(0, len(colors)-1)
color = colors[color_index]
turtle.pencolor(color)
turtle.pensize(random.randint(2, 7))
radius = random.randint(20, 200)
turtle.circle(random.choice([-1, 1]) * radius)
turtle.done()
The random.randint()
is a built-in function for obtaining a random integer number between the two numbers given as arguments, both included.
When accessing an element in a tuple, one has to provide an index number inside the pair of brackets following the name of the tuple variable. The first element of the tuple resides in position [0]
. If there are n elements in a tuple, the last element resides in position [n-1]
.
The random.choice()
method returns a single element from a sequence of items, including tuples.
The code section
color_index = random.randint(0, len(colors)-1)
color = colors[color_index]
turtle.pencolor(color)
above can simply be replaced by
turtle.pencolor(random.choice(colors))