所以我在搞弄Python。我想不出怎么做,所以如果您输入无效的用户名/密码,那么它将返回循环的顶部并再次从if语句开始。当我输入无效的用户名或密码时,它不会这样做。所以请有人帮我解释一下为什么?
values = ["User1", "123", "User2", "321", "User3", "132"]
print("Please log in to the program")
username = input("Please enter your username: ")
attempts = 3
while attempts >=1:
if username in values:
place = values.index(username)
passposition = int(place + 1)
print("Your username is valid.")
password = input("Now please enter the password to your account. Once again, passwords are case sensitive: ")
if password == values[passposition]:
print("The password is correct, welcome to the program")
else:
print("The password was invalid, please try again")
attempts -= 1
print("You now have ", attempts, " more attempts to log in with a valid username and password")
else:
print("Your username is invalid, please try again")
尝试-= 1 print(“您现在有尝试,使用有效用户名和密码登录的更多尝试”)
答案 0 :(得分:0)
这对您有用吗?
values = ["User1", "123", "User2", "321", "User3", "132"]
attempts = 3
print("Please log in to the program")
while attempts >=1:
#You need to ask for the username again, if you don't do this the variable is always assigned with a invalid value
#That's why it must be inside the loop
username = input("Please enter your username: ")
if username in values:
place = values.index(username)
passposition = int(place + 1)
print("Your username is valid.")
password = input("Now please enter the password to your account. Once again, passwords are case sensitive: ")
if password == values[passposition]:
print("The password is correct, welcome to the program")
#Once you have the right credentials you need to break the loop, if you comment the break you'll see that the programs asks again for the password
break
else:
print("The password was invalid, please try again")
attempts -= 1
print("You now have ", attempts, " more attempts to log in with a valid username and password")
else:
print("Your username is invalid, please try again")
attempts -= 1
print("You now have ", attempts, " more attempts to log in with a valid username and password")