如何将Python中的倒计时循环回while语句?

时间:2018-03-02 01:27:22

标签: python-3.x

password  = "1234"
guess = " "
count = 0
while count != 3 and guess != password:
     guess = input("Please enter your 4 digit pin: ")
     count = count + 1
     if guess == password:
          menu()
     elif count == 3:
          print("Number of tries maxed.")
          countdown()

     else:
          print("Your pin is denied, Try again")

上面是密码检查器的主要代码,它使用3个错误的密码锁定你,然后有倒数计时器3分钟。在倒计时之后,我希望它重置回菜单并允许您重新输入密码。

以下是倒计时的代码

def countdown():
 print("You have been locked out for 3 minutes. Please come back later and try again")
 delay = 180
 while delay >0:
     time.sleep(1)
     delay -=1

2 个答案:

答案 0 :(得分:0)

import time


def menu():
     print("This is the menu")


def countdown():
     print("You have been locked out for 3 minutes, try again later")
     delay = 180
     while delay > 0:
        time.sleep(1)
        delay -= 1
        print(delay)
     menu()




 password = "1234"
 guess = ""
 count = 0

 while count != 3 and guess != password:
        guess = input("Please enter your 4 digit pin: ")
        count += 1
        if guess == password:
             print("You got it")
        elif count == 3:
             print("Number of tries maxed out")
             countdown()

        else:
             print("Pin is denied, try again")

我刚刚在倒计时功能中添加了菜单功能(我不知道菜单功能中有什么,所以我只是创建了一个伪函数)。我在倒计时功能中将其添加到主循环之外,以便在倒计时达到0时立即调用菜单功能。

答案 1 :(得分:0)

只需要重置计数(count=0),如下所示:

password  = "1234"
guess = " "
count = 0
while count != 3 and guess != password:
     guess = input("Please enter your 4 digit pin: ")
     count = count + 1
     if guess == password:
          menu()
     elif count == 3:
          print("Number of tries maxed.")
          countdown()
          count = 0  # <<<<<<<<<< ONLY THIS NEEDS TO BE ADDED 
     else:
          print("Your pin is denied, Try again")

另外,为什么要在countdown()函数中创建一个延迟循环。可以这样做:time.sleep(180)

def countdown():
    print("You have been locked out for 3 minutes. Please come back later and try again")
    time.sleep(180)