def login():
logindetails = {'username':'Admin123' , 'password':'Pass123'}
username = input("please enter the username")
password = input("please enter the password")
if username == 'Admin123':
print ("username correct")
else:
print ("username incorrect")
if password == 'Pass123':
print ("password correct")
else:
print ("password incorrect")
login()
请告诉我在哪里放置while循环以及如何格式化代码以添加计数器。
答案 0 :(得分:0)
首先,您应该将用户名和密码变量初始化为空字符串以及计数器。
然后,你应该用for condition声明你的while循环,
之间的比较如果两者相同,你就会越过循环,如果没有,你必须再次询问用户输入并增加计数器。
换句话说:
username = ""
password = ""
counter = 0
WHILE username != logindetails['username'] AND password != logindetails['password']:
ASK for user inputs / DISPLAY error messages
INCREMENT counter
DISPLAY "logged after counter attempts"
它能回答你的问题吗?
答案 1 :(得分:0)
您可以这样做:
def login():
logindetails = {'username':'Admin123' , 'password':'Pass123'}
username = input("please enter the username")
password = input("please enter the password")
valid = False
while valid == False:
if username == 'Admin123' and password == 'Pass123':
print ("username and password correct")
valid = True
pass
else:
print ("username or password incorrect")
username = input("please enter the username")
password = input("please enter the password")
有效是bool所以循环不会停止,直到用户名和密码正确。
或者你可以有一个故障保险,如果用户输入的用户名和密码错误超过4次,就会把它们踢掉。
def login():
logindetails = {'username':'Admin123' , 'password':'Pass123'}
username = input("please enter the username")
password = input("please enter the password")
valid = False
count = 0
while count != 4 or valid == False:
if username == 'Admin123' and password == 'Pass123':
print ("username and password correct")
valid == True
pass
else:
print ("username or password incorrect")
count += 1
username = input("please enter the username")
password = input("please enter the password")
if valid == False:
print ("Sorry you had too many attempts to login. Try again later")