【问题标题】:Simple password check with limited retries简单的密码检查,重试次数有限
【发布时间】:2017-07-31 09:17:17
【问题描述】:

我正在尝试通过有限的重试次数进行简单的密码检查。

如果用户输入错误的密码,程序会提示重试(重试 3 次)。 3 次重试失败后,程序提示用户已达到最大重试次数。 如果用户键入正确的密码,程序将“授予访问权限”。

import sys
print (sys.version)
pssw = '' 
attempt = 0   

print('Please key in your password.') 

while (pssw != "remember") and (attempt < 3):    
    pssw = input()  
    attempt = attempt + 1

print ('No that is not correct. Try again.')

if attempt == 3:
    print ('Sorry you have reached maximum number of attempts')
    break

if (pssw == "remember"):
    print('Access Granted!') 

问题 #1

期望:输入正确的密码“Remember”后,程序应该打印输出“Access Granted”

但是程序输出:

3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06) 
Please key in your password.
remember
No that is not correct. Try again.
Access Granted!

问题 #2

期望:在最后一次尝试输入正确的密码“记住”后,程序应该打印输出“Access Granted”

但是程序输出:

Please key in your password.
test
No that is not correct. Try again.
test
No that is not correct. Try again.
remember
No that is not correct. Try again.
Sorry you have reached maximum number of attempts

我做错了什么?

【问题讨论】:

  • 你总是执行print ('No that is not correct. Try again.')。实际上,您记录的输出与您发布的代码不匹配。
  • 如果您需要一些帮助,您应该更新问题,以便代码和程序输出相互匹配。然后,您可以正确说明输出未满足您的期望。然后我们可以为您提供帮助。
  • 谢谢我从下面的帖子中发现流程是错误的。期望程序应该在前 2 次错误重试时执行 'No that is not correct. Try again。最后一次错误重试应该执行Sorry you have reached maximum number of attempts

标签: python python-3.x while-loop passwords


【解决方案1】:

我将解释您的错误,因为有人发布了另一种代码方法。 我认为重要的是你要理解你的错误,不要只是复制另一个代码。

首先,break 行不正确,因为 break 不能在循环之外,请改用 sys.exit()

问题 #1

如果您输入正确的密码,您的程序将退出循环并执行下一条语句:

print ('No that is not correct. Try again.')

if attempt == 3:
    print ('Sorry you have reached maximum number of attempts')
    break

if (pssw == "remember"):
    print('Access Granted!') 

所以它会打印“不,那不正确。再试一次。”。

检查尝试是否等于3。这不是因为您在第一次尝试时输入了正确的密码。

检查密码是否等于“记住”。是的,所以程序将打印“访问权限”。

问题 #2

您的第二个输出与您发布的代码不一致。
您发布的代码的正常输出是:

Please key in your password.
test
test
remember 
No that is not correct. Try again.
Sorry you have reached maximum number of attempts

这是您发布的代码的正常输出,但无论如何它都是错误的。

这是因为如果你输入了错误的密码,循环将继续,因此会再次询问你的密码而不打印任何内容。

【讨论】:

  • 感谢您解释我做错了什么并强调使用sys.exit() 而不是break 我已成功编辑代码并按预期工作。
猜你喜欢
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
  • 2013-05-18
  • 1970-01-01
  • 1970-01-01
  • 2022-11-05
  • 1970-01-01
  • 2021-03-22
相关资源
最近更新 更多