当我运行它时,它可以工作,但它说
"name 'select_place' is assigned to before global declaration"
当我删除第二个全局时,不会出现任何注释,但由于 select_place 不再是全局的,因此在我的最后一行代码中它不可读(如果选择)。 我对Python真的很陌生,理想情况下我想要一种不使用全局命令的方法,但搜索后我仍然找不到任何有帮助的东西。
我的代码:
def attempt(x):
if location =='a':
global select_place
select_place = 0
if location =='b'
global select_place
select_place = 1
place = ([a,b,c,d])
这是一些海龟图形的开始
def Draw_piece_a(Top_right):
goto(place[select_place])
最佳答案
需要先声明变量,另外函数代码可以更清晰:
select_place = False
def attempt(x):
global select_place
if location == 'a':
select_place = 0
elif location == 'b':
select_place = 1
另外,attempt()
没有返回值,这是你想要的吗?
关于Python 从函数内部更改外部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39270728/