无法在所描述的功能中分配变量

时间:2015-08-30 08:29:03

标签: python

有人可以告诉我如何将n分配给例如。 1在def。

PLsssssssss帮助。

全球范围内的设备n = x全局

它是Stuck On n = 0在非常开始时我的onkey命令并不会在全局重新分配n。  我无法解决它

全局n似乎不会影响我的

n仍然停留在0

我的代码现在是:

import turtle
turtle.left(90)
screen = turtle.Screen()
controls = 0
n = 0
screen.listen()
def w0():
  global n
  turtle.forward(100)
  n = 0
def w1():
  global n
  turtle.left(90),
  turtle.forward(100)
  n = 0
def w2():
  global n
  turtle.right(180)
  turtle.forward(100)
  n = 0
def w3():
  global n
  turtle.right(90)
  turtle.forward(100)
  n = 0
def d0():
  global n
  turtle.right(90)
  turtle.forward(100)
  n = 1
def d1():
  global n
  turtle.forward(100)
  n = 1
def d2():
  global n
  turtle.left(90)
  turtle.forward(100)
  n = 1
def d3():
  global n
  turtle.right(180)
  turtle.forward(100)
  n = 1
def s0():
  global n
  turtle.right(180)
  turtle.forward(100)
  n = 2
def s1():
  global n
  turtle.right(90)
  turtle.forward(100)
  n = 2
def s2():
  global n
  turtle.forward(100)
  n = 2
def s3():
  global n
  turtle.left(90)
  turtle.forward(100)
  n = 2
def a0():
  global n
  turtle.left(90)
  turtle.forward(100)
  n = 3
def a1():
  global n
  turtle.right(180)
  turtle.forward(100)
  n = 3
def a2():
  global n
  turtle.right(90)
  turtle.forward(100)
  n = 3
def a3():
  global n
  turtle.forward(100)
  n = 3
if n == 0:
  screen.onkey(w0, "w")
  screen.onkey(d0, "d")
  screen.onkey(s0, "s")
  screen.onkey(a0, "a")
  print(n)
if n == 1:
  screen.onkey(w1, "w")
  screen.onkey(d1, "d")
  screen.onkey(s1, "s")
  screen.onkey(a1, "a")
  print(n)
if n == 2:
  screen.onkey(w2, "w")
  screen.onkey(d2, "d")
  screen.onkey(s2, "s")
  screen.onkey(a2, "a")
  print(n)
if n == 3:
  screen.onkey(w3, "w")
  screen.onkey(d3, "d")
  screen.onkey(s3, "s")
  screen.onkey(a3, "a")
  print(n)

1 个答案:

答案 0 :(得分:0)

您需要将n声明为全局变量...例如:

def s3():
    global n
    turtle.left(90)
    turtle.forward(100)
    n = 2

在Python中,如果存在赋值且未明确声明变量global,那么它认为它是局部变量。