创建每30秒重置一次的计数器

2024-04-25 22:20:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个计数到30的函数,但当它达到30时,我想将它重置为起始点。你知道吗

def countdown():
  global countDown
  countDown = int(time.time() - start_time)
  return countDown % 30

然后我想把它印成那样。你知道吗

print("You have " + str(30 - countdown()) + " time") 

它可以工作,但是当它达到0时,它会一直计数到0以下,比如-1,-2,并且它不执行模运算。所以它不会自动复位。在这种情况下我能做什么?你知道吗

所需案例:30 29。。。。3 2 1 0 30 29 28 最近的病例:30 29。。。2 1 0-1-2


Tags: 函数youreturntimedefhaveglobalstart
3条回答

没有使用模运算符(countDown % 30)重置计数器。试试看

import time
def countdown(i):
  counter = i
  while True:
    if (counter == i):
      counter = 0
    print(counter)
    counter = counter + 1
    time.sleep(1)

countdown(30)

尽量避免使用全局变量。另外,使用4个空格缩进。 我会使用时间长度作为输入。你知道吗

from time import time

def do_something():
    pass

def get_time(start_time):
    # returns how much time did it pass from event that started at start_time
    return time() - start_time

def countdown(countDown):
    start_time = time()
    # this is counter that attains consecutive values [0, 1, ..., countDown]
    current_count = 0
    while current_count < countDown:
        print(countDown - current_count, end=' ')
        while get_time(start_time) - current_count < 1:
            do_something()
            #warning: if do_something takes significant anount of
            #time forthcoming print won't be correct
        current_count += 1
    print(countDown - current_count, end=' ')
    return current_count

countdown(7)
countdown(5)

也是

print("You have " + str(30 - countdown()) + " time") 

我不清楚。无论你想在剧本里什么地方使用它。你知道吗

我从你的密码里得到了什么

import time
start_time = time.time()
def countdown():
  global countDown
  countDown = int(time.time() - start_time)
  return countDown % 30

print("You have " + str(30 - countdown()) + " time")

正在https://www.python.org/shell/上完美工作
无法重现你的问题。或者你的问题不是代码!你知道吗

相关问题 更多 >