基本上我正在创建一个允许用户创建密码和用户名的程序。如果他们这样做,那么程序将要求他们登录。如果他们输入的密码和用户名是正确的,它将停止并说欢迎。它工作但它在程序启动之前给我一个错误然后它正常启动。
>>>
Warning (from warnings module):
File "C:\Python34\password.py", line 8
global username
SyntaxWarning: name 'username' is assigned to before global declaration
>>>
Warning (from warnings module):
File "C:\Python34\password.py", line 29
global password
SyntaxWarning: name 'password' is assigned to before global declaration
import time
def usrname():
total=0
while total != 600:
time.sleep(1)
username=input("Create a username(must be 6 chatacters long):")
global username
if len(username)== 6:
break
else:
time.sleep(1)
print("Your username is invalid")
print("Try again")
total=total+1
def psw():
totalP=0
while totalP != 6:
time.sleep(1)
print("the password must be 5-8 characters long")
print("Contains atlease 1 capital letter")
password=input("please enter your password:")
password2=input("please enter your password again")
global password
if len(password)>5 and len(password)<8:
if password.title() == password:
if password.title()==password2:
break
else:
print("Your password is invalid, please try again")
totalP=totalP+1
option=input("Do you want to create an account(Y/N)")
if option.title()=="Y":
usrname()
psw()
else:
pass
print("Hello please log in")
total3=0
while total3 < 12:
log1=input("what is your username?")
log2=input("what is your password?")
if log1 != username:
print("your username is invaild, please try again")
total3=total3+1
if log2 != password:
print("your password is invaild, please try again")
total3=total3+1
else:
break
if total3 > 12:
print("you must wait 2 days before you could enter your username again")
else:
print("hello, wellcome to my program")
答案 0 :(得分:1)
这是有原因的。您的变量未在要使用它们的范围内初始化。username
和password
变量在函数内初始化,但随后它们的作用域结束。但是你的代码仍然有效,因为你的函数名称相同,所以写你的时候
if log1 == username:
实际上是这样的:
if log1 == <function username at 0x7f26d33dff28>:
这是对该功能的引用。
您需要做的是在调用用户名和密码方法之前初始化全局范围中的变量。还要考虑将它们命名为其他内容。
这样做:
usrname=""
pwd=""
username()
password()
并更改这些变量的代码。
有关范围信息,请参阅https://docs.python.org/2/reference/executionmodel.html。
答案 1 :(得分:0)
if log1 != username:
print("your username is invaild, please try again")
它显示无效,因为上面引用“username”基本上是对代码中定义的函数名“username()”的调用,它返回一个分配给函数名变量的引用hexacode值。它永远不会等于您期望的用户名。尝试下面的代码打印正在比较的用户名,您将知道它无法正常工作。
if log1 != username:
print username
print("your username is invaild, please try again")