2

Every time the turtle is clicked, how would I have it increment the variable clicks by 1:

import turtle
jeff = turtle.Turtle()
jeff.shape("turtle")
jeff.color("blue")
clicks=0


def left(x,y): 
    jeff.left(90) 
    clicks=clicks+1
    print "you have"+clicks+"clicks."


jeff.onclick(left)

When I type this in, on the line clicks=clicks+1 it gives me:

UnboundLocalError: local variable 'clicks' referenced before assignment

1

1 Answer 1

1

The variable clicks is global. Any function that wants to modify a global variable has to declare that variable global:

from turtle import Turtle, mainloop

clicks = 0

def left(x, y):
    global clicks

    jeff.left(90)
    clicks += 1
    print "you have " + str(clicks) + " clicks."

jeff = Turtle()
jeff.shape("turtle")
jeff.color("blue")

jeff.onclick(left)

mainloop()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.