我在代码末尾遇到一个break语句时遇到麻烦。如果我在那里,那么当用户输入错误的用户名和/或密码时,程序将退出并且不会继续while循环。如果不存在,则在用户成功登录后,将提示用户再次输入用户名,而该用户名仅应退出程序。我应该进行哪些更改才能使其全部正常工作?
我尝试放入和取出break语句并放入while循环。
#login
count = 0
if welcome == "y":
while True:
while count < 3:
use = input("Username:")
pwd = input("Password:")
found_username = False
with open("Credentials.txt", "r") as credentials_file:
for line in credentials_file:
username_login, password_login = line.strip().split(':')
if use == username_login:
found_username = True
if pwd == password_login:
print("welcome you are now logged in ")
break
else:
print("Password is incorrect!")
count += 1
if count == 3:
print("Attempts exceeded")
break
if not found_username:
print("Username and or password do not exist!")
count += 1
if count == 3:
print("Attempts exceeded")
else:
break
break
\\\\ 用户成功登录后,程序应退出。如果他们输入了错误的用户名和/或密码,则应提示用户再次输入用户名和密码,直到正确无误为止(最多3次)
答案 0 :(得分:0)
break
语句是无条件执行的,因此您永远不会重复循环。
仅当found_username
为真时才执行,因此将其放在最后一个else:
的{{1}}块中。
if
答案 1 :(得分:0)
考虑到您当前构建代码的方式,您实际上需要两个循环,一个循环监视尝试次数,另一个循环检查有效凭据。话虽如此,我强烈建议将两个循环解耦,以使您更容易地推断出问题所在。这就是为什么发布代码如此重要的原因-它使您可以更轻松地发现错误。
此外,您可以利用其他一些Python概念。 (1)在此处引发异常以引发特定错误(例如,用户名不存在而密码不正确),(2)分解continue
和break
之间的区别。 continue
用于跳到循环的下一个迭代。 break
用于完全打破循环。
对于您的代码,我建议类似以下内容:
def authenticate(username, password):
with open("Credentials.txt", "r") as credentials_file:
for line in credentials_file:
username_login, password_login = line.strip().split(':')
if username_login == username and password_login == password:
return True # Everything matches!
elif username_login == username and password_login != password:
raise Exception('Password is incorrect!')
else:
continue # Skip to next line in credentials file
raise Exception('Username does not exist')
if welcome == 'y':
is_authenticated = False
for i in range(3):
username = input('Username:')
password = input('Password:')
try:
authenticate(username, password)
is_authenticated = True
break # Don't need to provide another attempt
except Exception as e:
print(e) # Print error
if is_authenticated:
print('Welcome you are now logged in')
else:
print('Attempts exceeded!')