【问题标题】:Password system. How do I allow 3 incorrect guesses while allowing the program to continue if the guess is correct密码系统。如果猜测正确,如何在允许程序继续运行的同时允许 3 次错误猜测
【发布时间】:2016-08-11 09:58:15
【问题描述】:

程序需要允许用户 3 次错误的尝试写入密码。但是,如果他们的密码尝试正确,我希望程序打印“nice”。

这是我目前所拥有的:

def main():

    n = 2

    for i in range(0, 3, 1):

        attempt = input('Enter password: ')


        if attempt != 'password':
            print('Incorrect. ' + str(n) + ' attempts left')

        n = int(n) - 1

        else:
            print('nice')

【问题讨论】:

  • 您要查找的单词是break

标签: python loops passwords


【解决方案1】:
max_retries = 3
for i in range(max_retries):
    passwd = input('\nEnter password: ')
    if passwd == 'password':
        print('\nnice')
        break
    print('Incorrect.  %d attempts left' % (max_retries-i-1))

【讨论】:

    【解决方案2】:
    n = 2
    for i in range(0, 3, 1):
        attempt = raw_input('Enter password: ')
        if attempt != 'password':
            print('Incorrect. ' + str(n) + ' attempts left')
            n = int(n) - 1
        elif n > 0:
            print('nice')
        else:
            print('no attempts left')
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。不鼓励仅使用代码回答。
    • 老兄,我认为这个答案不需要解释。但无论如何,请随意对我投反对票:D
    • 老兄投反对票的不是我,我只是想帮你,你知道,避免投反对票。
    【解决方案3】:
    for x in range(3):
    pass_correct=False
    password = "password"
    attempt=raw_input("Enter password: ")
    if attempt == password:
         pass_correct=True
         break
    else:
        print "incorrect, " + str(2-x) + " attempts left"
    if pass_correct:
        print "nice"
    else:
        print "no attempts left"
    

    简洁

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      相关资源
      最近更新 更多