14.4. Using Random NumbersΒΆ

We can generate random numbers in Python using the randrange function in the random library. This function takes an optional starting value (inclusive) and the ending value for the range (exclusive). We can use random numbers in games to add an element of chance. We can also use random numbers to move the turtle to random positions as shown below. We are using conditionals to alternate the drawing color each time the turtle moves.

Can you modify the code above to use 3 different colors? You can use num % 3 to give you 3 possible results.

In the first section this chapter we created the chevron image on the left using turtles. Modify the code to create the stampped image on the right. The turtles will stamp/draw in blue and green. The color will be chosen at random.

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

Show Comments

Note

Discuss topics in this section with classmates.

Show Comments
You have attempted 1 of 5 activities on this page