我的问题是我在这个脚本中一直得到一个未定义的全局名称错误:
import time
def cls():
print(("\n")*100)
#Registers the Username and Password for the user.
def registerPro():
cls()
username=str(input("Enter your Username here: "))
password=str(input("Enter your Password here: "))
confirm=str(input("Please confirm your Password: "))
if password==confirm:
cls()
print("Thank you for registering at Apex Industries!")
time.sleep(3)
loggingIn()
else:
cls()
print("Your passwords do not match, please re-register.")
time.sleep(3)
registerPro()
return username, password
#Is called by getUsername. If the user entered the password correctly then the login is successful.
def getPass(password):
cls()
confirmPass=str(input("Enter your password: "))
if confirmPass==password:
cls()
print("You have logged in successfully.")
else:
cls()
print("Wrong Password. Try again")
getPass()
#Makes sure the username is in the database.
def getUsername(username):
cls()
confirmUser=str(input("Enter your username: "))
if confirmUser==username:
getPass(password)
else:
cls()
print("No username with that name in the database.")
time.sleep(3)
loggingIn()
#The login for the main program.
def loggingIn():
cls()
print("Hello and welcome to the Apex Industries login/register page.")
print(" Please choose to either Login or Register.")
print()
regLog=str(input("Type Login or Register for your choice: "))
if regLog=='Login':
getUsername(username)
elif regLog=='Register':
registerPro()
else:
cls()
print("That is not a valid option. Try again.")
time.sleep(3)
loggingIn()
loggingIn()
我的追溯给了我这个:
Traceback (most recent call last):
File "C:/Users/Evu/Desktop/Python/testforLogin", line 59, in <module>
loggingIn()
File "C:/Users/Evu/Desktop/Python/testforLogin", line 13, in loggingIn
registerPro()
File "C:/Users/Evu/Desktop/Python/testforLogin", line 29, in registerPro
loggingIn()
File "C:/Users/Evu/Desktop/Python/testforLogin", line 11, in loggingIn
getUsername(username)
NameError: global name 'username' is not defined
我做错了什么?我想将username导入到我创建的getUsername()函数中。请记住,我是脚本新手,我只是想在自己的时间学习这个,这只是一个测试脚本。任何建议都很棒。
答案 0 :(得分:1)
您正在使用名为getUsername
的变量作为参数调用username
函数,该参数在此时未定义。
实际上,它在getUsername
函数中定义,但不是username
。相反,最终成为包含真实用户名的变量的是confirmUser
。在那种情况下这种情况有意义,但是username
应该包含有效/已注册的用户名。反过来,实际上应该是某种包含多个用户名的列表,为此可以使用专用函数。
有趣的是:你在regLog-thing的开头就做得很好。你在那里通过输入定义regLog,然后检查它的值。
您肯定应该再次查看有关变量,函数(及其参数)的文档,以及一般的基础知识。哦,它应该是raw_input()
而不是input()
。至少在这种情况下。
这将是我快速而肮脏(且不完整)的方法:
registeredusers = ['john.doe', 'peter.parker', 'bruce.banner']
def getUsername():
global registeredusers
loginname = str(raw_input("Enter username: "))
if loginname in registeredusers:
return True
else:
return False
def loggingIn():
regLog = str(raw_input("Login or Register? "))
if regLog == 'Login':
if getUsername():
print "Yay! Logged in"
else:
print "Login failed"
elif regLog == 'Register':
# do stuff
pass
else:
# do stuff
pass
loggingIn()
答案 1 :(得分:0)
您在loggingIn()
至getUsername(username)
进行通话时尚未初始化用户名 - 您要验证哪个用户名,来自何处?鉴于它无法找到本地username
它在全局命名空间中查找并且无法在那里找到它 - 因此出错。