2

在学习 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()        
4

1 回答 1

4

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

当您的用户正确时,您应该离开 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()
于 2020-12-17T08:02:44.407 回答