停止运行一定次数的循环

时间:2014-11-20 14:38:53

标签: python loops

我几乎整个上午都在寻找可以帮助我的代码,但很难找到类似的代码! 我必须创建一个银行系统,要求用户输入用户名和密码。 如果输入3次,系统将关闭。 到目前为止,我已经让我的程序知道密码/用户名是否正确。 现在我只需要弄清楚如何使它在3次不正确的尝试后运行和停止。 非常感谢对此提供的任何帮助!感谢

代码:

username = "bank_admin"
password = "Hytu76E"

usernameGuess = raw_input("Please enter your username: ")
passwordGuess = raw_input("Please enter the password: ")


while (username != usernameGuess or password != passwordGuess):
    print ("Please try again.")

    usernameGuess = raw_input("Please enter your username: ")
    passwordGuess = raw_input("Please enter your password: ")

print ("Password accepted. Access Authorized.")

1 个答案:

答案 0 :(得分:1)

您可以添加一个计数器,以查看他们猜错密码的次数。然后将其用作while循环中的另一个条件。

incorrectGuesses = 0
correct = False
while (not correct and incorrectGuesses < 4):
    usernameGuess = raw_input("Please enter your username: ")
    passwordGuess = raw_input("Please enter your password: ")
    correct = ((username == usernameGuess) and (password == passwordGuess))
    if not correct:
        print ("Please try again.")
        incorrectGuesses += 1