使用输入时出现名称错误-Python 2.7
我制作了一个脚本,用于检查变量是否与输入变量相同:使用输入时出现名称错误-Python 2.7,python,python-2.7,nameerror,Python,Python 2.7,Nameerror,我制作了一个脚本,用于检查变量是否与输入变量相同: def password(): userPassword = str(input("Type Your Password: ")) if userPassword == storedPassword: print 'Access Granted' else: print 'Access Denied' password() 然而,每当我为输入输入一个字母时,它就会抛出一个
def password():
userPassword = str(input("Type Your Password: "))
if userPassword == storedPassword:
print 'Access Granted'
else:
print 'Access Denied'
password()
然而,每当我为输入输入一个字母时,它就会抛出一个NameError,但是它可以处理数字
错误:
Traceback (most recent call last):
File "C:\Users\***\Desktop\Test\Script.py", line 16, in <module>
password()
File "C:\Users\***\Desktop\Test\Script.py", line 9, in password
userPassword = str(input("Type Your Password: "))
File "<string>", line 1, in <module>
NameError: name 'f' is not defined
对于Python2.7,您需要使用原始输入而不是输入,输入实际上会将输入作为Python代码进行计算。原始输入返回用户输入的逐字记录字符串 请参见您需要在Python2上使用原始输入而不是输入 使用输入尝试评估您传递的任何内容。对于整数,它只解析为该整数。对于字符串,它将尝试查找该变量名,这将导致错误 您可以通过键入“密码”(如password)来确认这一点,该密码将使您的输入调用返回对密码函数的引用 相反,原始输入总是返回一个包含用户键入的字符的字符串。从您试图将用户键入的任何内容转换回字符串来看,这正是您想要的
userPassword = raw_input("Type Your Password: ")
在任何人都可以帮助您之前,您需要修复问题中的缩进。哎呀,谢谢,我没有看到:它在我的机器上运行良好..是因为您忘记在上下文中指定storedPassword吗?请更新您的答案以包含完整的错误。