<p>考虑到当前构建代码的方式,实际上需要两个循环,一个用于监视尝试次数,另一个用于检查有效凭据。也就是说,我强烈建议将这两个循环解耦,以便于您对问题进行推理。这就是为什么分解代码如此重要的原因—它使您能够更容易地发现错误</p>
<p>此外,还可以利用一些附加的Python概念(1) 在这里引发异常以抛出特定错误(例如用户名不存在而密码不正确),(2)分解<code>continue</code>和<code>break</code>之间的差异<code>continue</code>用于跳转到循环的下一个迭代<code>break</code>用于完全脱离循环</p>
<p>对于您的代码,我建议如下:</p>
<pre><code>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!')
</code></pre>