tags:

views:

70

answers:

1

I'm trying to create a randomly moving turtle here by following these steps in a function I've called drunk_turtle():

Repeat the following as many times as you like:

  • Randomly choose an integer, called rand_num, from -1 to 1 (i.e. randomly set rand_num to be -1, 0, or 1)
  • Make the turtle turn right rand_num * 90 degrees;
  • Go forward 5, 10, or 15 --- choose this value at random. 5 = 1*5, 10 = 2*5, 15 = 3*5, ...

How do I make code that does this? I don't really get how to get my random integer or get it to pick randomly 5, 10, or 15. Any help is appreciated. Thanks!

+1  A: 

You can find all of that information in the Python random manual.

random.randint(a, b)

Return a random integer N such that a <= N <= b.

So you would do random.randint(-1,1) to get a number from -1, 0, or 1.

To get 5, 10, or 15, just do 5 * random.randint(1,3).

If you had a more complicated set of numbers to choose from -- say (6, 25, or 33) -- you can do random.choice([6, 25, 33]).

Mark Rushakoff
Thanks a bunch, that answered my question!
Benjamin