[英]Variable referenced before assignment error
我试图使我的代码要求输入密码并接收它,如果密码正确,则将发生某些事情,否则将发生其他事情,当我尝试代码时,它在第10行和第18行给了我一个错误:
if (password == 'xxxx'):
UnboundLocalError: local variable 'password' referenced before assignment
这是代码:
import random
def askforPassword():
print('Welcome to the Machine!')
print('Enter the password: ')
password = input()
def getPassword():
while passwordTry != 0:
if (password == 'xxxx'):
print('Correct')
else:
passwordTry -= 1
print('INCORRECT!')
passwordTry = 5
askforPassword()
getPassword()
由于您正在询问为什么它不起作用,因此让我们看一下您得到的错误:
Traceback (most recent call last):
File "pw.py", line 18, in <module>
getPassword()
File "pw.py", line 10, in getPassword
if (password == 'xxxx'):
UnboundLocalError: local variable 'password' referenced before assignment
这意味着您正在尝试访问局部变量'password'
,但尚未创建任何此类局部变量。
如果要使用全局变量,请明确声明:
def getPassword():
global password
while passwordTry != 0:
if (password == 'xxxx'):
print('Correct')
else:
passwordTry -= 1
print('INCORRECT!')
但这仍然行不通,因为也没有人设置该全局变量。 您还需要更改askforPassword
:
def askforPassword():
global password
print('Welcome to the Machine!')
print('Enter the password: ')
password = input()
这仍然有很多问题。 例如,您只调用一次askforPassword
,而不是每次循环调用一次,因此只询问一次,然后打印INCORRECT!
5次。 另外,最好不要使用全局变量,而是将askforPassword
return
密码,并将其存储在getPassword
的本地变量中。
def askforPassword():
print('Welcome to the Machine!')
print('Enter the password: ')
password = input()
return password
def getPassword():
while passwordTry != 0:
password = askforPassword()
if (password == 'xxxx'):
print('Correct')
else:
passwordTry -= 1
print('INCORRECT!')
而且您可能也想从getPassword
返回某些内容,因此无论调用它的人都知道您是成功还是失败。
您可能需要考虑将逻辑稍微更改为以下内容:
import random
def askforPassword():
print('Welcome to the Machine!')
print('Enter the password: ')
password = input()
return password
def getPassword():
passwordTry = 5
while passwordTry:
if (askforPassword() == 'xxxx'):
print('Correct')
break
else:
passwordTry -= 1
print('INCORRECT!')
getPassword()
import random
password=-1
passwordTry=5
def askforPassword():
global password # define as global
print('Welcome to the Machine!')
print('Enter the password: ')
password = raw_input() # python < 3 ? use raw_input
def getPassword():
global password # not func. local
global passwordTry # not local, global
while passwordTry != 0:
askforPassword() # ask in each iteration
if (password == 'xxxx'):
print('Correct')
break # don't ask if correct
else:
passwordTry -= 1 # not password, passwordTry
print('INCORRECT!')
getPassword()
无论您最终要做什么,而不是input()
或raw_input()
,请确保使用标准的Python模块getpass
代替(这样它就不会回显到stdout):
import getpass
foo = getpass.getpass('Enter the password: ')
print('You typed: %s'%foo)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.