首页 > 解决方案 > 尝试创建在 6 次错误输入用户名和密码后退出的程序

问题描述

在学习 Python 的开始阶段,我遇到了一些障碍

我正在尝试创建一个要求特定用户名和密码的程序。在 6 次错误尝试后,它将退出程序。当我输入正确的信息时,示例代码可以正常工作。我遇到的问题是用户名正确但密码不正确。我希望它打印“密码不匹配”并重新询问密码。它带我回到程序的开头并再次询问我的用户名。有什么想法可以解决这个问题吗?先感谢您!

代码也可以在这里找到:https ://pastebin.com/4wSgB0we

import sys
incorrect = 0
max_tries = 6

choices = ['Drake', 'swordfish']

run = True

while run:
    while incorrect < max_tries:
       user_input = input('Please enter username: ')
       if user_input not in choices:
          incorrect += 1
          print(f"{user_input} is incorrect. Please try again.")
       else:
          print(f"Welcome back {user_input}.")
          pass_input = input('Please enter password: ')
    
          if pass_input not in choices:
             incorrect += 1
             print("Password does not match. Please try again")
          else:
             run = False
             print('Access granted')
             sys.exit()
            
 if incorrect == max_tries:
    sys.exit()        

标签: pythonpython-3.x

解决方案


如果它没有帮助您解决问题。
我会修改。

当您的用户正确时,您应该离开 While。
如果您不离开 While,将再次询问用户帐户。

while run:
    while incorrect < max_tries:
        user_input = input('Please enter username: ')
        if user_input not in choices:
            incorrect += 1
            print(f"{user_input} is incorrect. Please try again.")
        else:
            print(f"Welcome back {user_input}.")
            break
    while incorrect < max_tries:
        pass_input = input('Please enter password: ')
        if pass_input not in choices:
            incorrect += 1
            print("Password does not match. Please try again")
        else:
            run = False
            print('Access granted')
            sys.exit()

    if incorrect == max_tries:
        sys.exit()

推荐阅读