Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法在描述的函数中分配变量_Python - Fatal编程技术网

Python 无法在描述的函数中分配变量

Python 无法在描述的函数中分配变量,python,Python,有人能告诉我如何在def中为例如1分配n吗 PLSSS帮助 a如何处理全局def不能设置为全局n=x 它被卡在n=0上,在非常短的时间内被禁用,我的onkey命令不会全局重新分配n。 我修不好 全局n似乎不会影响我的n n仍然停留在0上 我的代码是: import turtle turtle.left(90) screen = turtle.Screen() controls = 0 n = 0 screen.listen() def w0(): global n turtle.forw

有人能告诉我如何在def中为例如1分配n吗

PLSSS帮助

a如何处理全局def不能设置为全局n=x

它被卡在n=0上,在非常短的时间内被禁用,我的onkey命令不会全局重新分配n。 我修不好

全局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)
您需要将n声明为全局变量。。。例如:

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

在Python中,如果存在赋值且变量未显式声明为全局变量,则假定它是局部变量。

global n不起作用global n起作用,但代码中还有其他问题。我无法发布工作版本,因为问题已经解决了。每次n发生变化时,您需要调用onkey函数。一种方法是将if语句放入函数中&在每个函数的末尾调用该函数。你需要在你的程序结束时有一个turtle.mainloop,除非你是在空闲或类似的状态下运行它。谢谢你终于修好了