KINGMORRIS321
KINGMORRIS321

Reputation: 1

Randomly chose an action (definition) with random.choice()

Code doesn't work like it should. It is just a small thing i would like to learn as a new coder:

import turtle
import random
me=turtle.Turtle()
def up_right(): 
   me.right(90)
   me.forward(100)

def down_right():
me.right(90)
me.forward(100)
choose = (up_right(), down_right)
random.choice(chose)

It should pick one and do it but it picks them both. I've tried random.sample and random.choice but cant get them to work.

Upvotes: 0

Views: 632

Answers (2)

cdlane
cdlane

Reputation: 41872

I see three issues with your code. The first two folks have pointed out already, the choose vs chose typo and leaving the parens () on upright when refering to it as a function (up_right(), down_right).

The third is that up_right and down_right both implement the same motion, so even if the rest of your code worked, you wouldn't see any difference! Below's a rewrite that fixes this issue:

from turtle import Screen, Turtle
from random import choice

def up_right(turtle):
    turtle.setheading(90)
    turtle.forward(100)

def down_right(turtle):
    turtle.setheading(270)
    turtle.forward(100)

choices = [up_right, down_right]

screen = Screen()

me = Turtle('turtle')

choice(choices)(me)

screen.mainloop()

Run it several times and you'll see sometimes the turtle heads up the screen, sometimes it heads down.

Upvotes: 0

Endyd
Endyd

Reputation: 1279

Besides the typo of choose... My suggestion is that after you create a tuple of functions and choose the function using random.choice(), you should make a call to the function chosen by the random.choice().

# Notice I removed the () after up_right so it doesn't make the function call on this line
choose = (up_right, down_right) 
# random.choice will return one of the two, and then the () will call whatever function was chosen
random.choice(choose)() 

Upvotes: 2

Related Questions