Search code examples
pythonturtle-graphicspython-turtle

How to make a function do a random event over and over


What I mean is when I declare a function like

import turtle
import random
turt = turtle.Turtle()
x = random.randint(-300,300)
y = random.randint(-300,300)
def randomspot():
    turt.penup()
    turt.goto(x,y)
    turt.pendown()

and declear the function twice, it goes to the same spot. What should I do?


Solution

  • import turtle
    import random
    turt = turtle.Turtle()
    
    def randomspot():
        turt.penup()
        turt.goto(
          random.randint(-300,300),
          random.randint(-300,300)
        )
        turt.pendown()
    

    you need to create a new random number every time you run the function, before you were defining x and y then running the same function. x and y never have a chance to change.