我正在尝试让我的代码要求输入密码并接收密码,如果密码是正确的,如果不会发生其他事情会发生某些事情,当我尝试我的代码时,它会在第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()
答案 0 :(得分:5)
既然你问为什么它不起作用,让我们来看看你得到的错误:
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
返回一些东西,所以无论谁调用它都知道你是成功还是失败。
答案 1 :(得分:3)
您可能想要将逻辑略微改为:
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()
答案 2 :(得分:1)
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()
答案 3 :(得分:0)
无论您最终做什么,而不是input()
或raw_input()
,请确保使用标准Python模块getpass
(以便它不会回显到stdout):< / p>
import getpass
foo = getpass.getpass('Enter the password: ')
print('You typed: %s'%foo)