Python 从函数内部更改外部变量

标签 python

当我运行它时,它可以工作,但它说

"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/

相关文章:

Python OpenCV 3 : how to use cv2. CV_COMP_HELLINGER

python - Linux - 显示一些命令的内存

android - 使用 Appium-Python 在 Android 应用程序中垂直滚动

python - 关键错误 = client_id -- django

python - Pandas 数据帧 : Replace values in a dataframe with values from corresponding column vector of a different dataframe

python - 使用 pyglet 加载图像将一些透明像素变成白色

python - 我怎样才能用lxml解析html

python - Pygame - 检测组中的碰撞时出错

python - 在管理页面中编辑 M2M 的两侧

python - 在不同条件下选择numpy数组中的数据