Python 3:“赋值前引用的局部变量”(Python 3: “Local Variable referenced before assignment”)

编程入门 行业动态 更新时间:2024-10-28 01:12:39
Python 3:“赋值前引用的局部变量”(Python 3: “Local Variable referenced before assignment”)

已经看过其他答案,似乎无法解决这个问题。

这是我的完整代码: http : //pastebin.com/tW1kntG3

有问题的代码在这里:

#Define the variables global currentLoc currentLoc=0

(显然,破坏代码的部分是第37行。)

if call=="move": print("Move where?") print("") if currentLoc==0: print("Left: You cannot move left.") print("Right: " + locName[currentLoc+1]) elif currentLoc>1: print("Left: " + locName[currentLoc-1]) print("Right: " + locName[currentLoc+1]) print("") print("Move left or right? Enter your choice.") direction = input("?: ") if direction=="left": print("Moved left.") if currentLoc>1: currentLoc = currentLoc-1 pass elif direction=="right": currentLoc = currentLoc+1 pass pass

我的错误:

if currentLoc==0: UnboundLocalError: local variable 'currentLoc' referenced before assignment

already looked at other answers and can't seem to fix this.

Here's my full code: http://pastebin.com/tW1kntG3

The code in question lies around here:

#Define the variables global currentLoc currentLoc=0

(The part that is breaking the code, apparently, is line 37.)

if call=="move": print("Move where?") print("") if currentLoc==0: print("Left: You cannot move left.") print("Right: " + locName[currentLoc+1]) elif currentLoc>1: print("Left: " + locName[currentLoc-1]) print("Right: " + locName[currentLoc+1]) print("") print("Move left or right? Enter your choice.") direction = input("?: ") if direction=="left": print("Moved left.") if currentLoc>1: currentLoc = currentLoc-1 pass elif direction=="right": currentLoc = currentLoc+1 pass pass

My error:

if currentLoc==0: UnboundLocalError: local variable 'currentLoc' referenced before assignment

最满意答案

您需要在函数中声明全局。 Python确定每个范围的名称范围 。 如果您在函数中指定名称(或将其用作导入目标,或for目标或参数等),则除非另有说明,否则Python会将该名称设置为本地名称。

因此,在全球范围内使用global是毫无意义的,因为Python已经知道它是全局的。

将global语句添加到尝试更改名称的每个函数中:

def displayMessage(call): global currentLoc

You need to declare a global in the function. Python determines name scope per scope. If you assign to a name in a function (or use it as an import target, or a for target, or an argument, etc.) then Python makes that name a local unless stated otherwise.

As such, using global at the global level is rather pointless, because Python already knows it is a global there.

Add your global statement into each of function that tries to alter the name:

def displayMessage(call): global currentLoc

更多推荐

本文发布于:2023-04-27 13:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1327106.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:赋值   变量   局部   Python   assignment

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!