Random numbers in Python
Python has a special module that will generate random numbers. To use it you must import it first
import turtle,random
It's the same as importing the Turtle module. We've now got two import modules so we put them both on the first line and separate them with commas.
Generating a random number
The most useful command is randrange(start, finish)
Here's a program fragment with a function that will get a random colour.
Note that random.randrange(7) will give numbers between 0 and 6 - it will never produce a 7
Here's a program fragment with a function that will get a random colour.
Note that random.randrange(7) will give numbers between 0 and 6 - it will never produce a 7
import turtle,random
colors = ("red","green","blue","yellow","black","purple","cyan","magenta")
def randomcolor():
randomnumber = random.randrange(7)
turtle.color(colors[randomnumber])
Challenge 1
Here's the main program. You can copy this
while True: Your challenge is to make the functions that will make it work and produce the output on the right
More challenges |