繁体   English   中英

如何在Python中制作倒数计时器而无需输入?

[英]How to make countdown timer in Python without input?

我一直在尝试为 python 中的游戏创建倒数计时器,但是我不确定如何在不包括代码开头的时间输入问题的情况下对其进行编码。

到目前为止,代码看起来像这样

import time
import datetime
 
# Create class that acts as a countdown
def countdown(s):
 
    # Calculate the total number of seconds
    total_seconds = s
 
    # While loop that checks if total_seconds reaches zero
    # If not zero, decrement total time by one second
    while total_seconds > 0:
 
        # Timer represents time left on countdown
        timer = datetime.timedelta(seconds = total_seconds)
        
        # Prints the time left on the timer
        print(timer, end="\r")
 
        # Delays the program one second
        time.sleep(1)
 
        # Reduces total time by one second
        total_seconds -= 1
 
    print("You have been caught.")
 
# Inputs for hours, minutes, seconds on timer
s = input("Enter the time in seconds: ")
countdown(int(s))
exit()

我想编写代码,以便用户按下回车后它会自动倒计时 10 秒。 有任何想法吗?

如果我正确理解您的问题,您只希望用户按下回车键而不是实际输入数字? 然后您可以硬编码时间值并使用该值调用 function,同时使用空输入调用来等待按键。

input("Press enter to continue...")
countdown(10)
exit()

在这里,您不会将input中的值存储在任何地方,而只是使用input function 来阻止,直到用户按下回车键。

你可以这样做:

import time


def countdown(time_sec):
    while time_sec:
        minutes, secs = divmod(time_sec, 60)
        time_format = f'{minutes}:{secs}'
        print(time_format, end='\r')
        time.sleep(1)
        time_sec -= 1

    print("stop")


countdown(5)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM