用户输入以停止 while 循环

时间:2021-06-18 06:33:56

标签: python

我目前正在制作一个秒表功能,用户必须输入 1 开始和 2 停止秒表。我想知道当 while 循环进行时如何实现停止功能,因为我尝试的任何方法都不起作用。

这是我正在处理的秒表代码:

second = 0
minute = 0
hour = 0
millisecond = 0

start = input("Press 1 to start and 2 to stop: ")

while True:
if start == "2":
  break
else:
  print("%02d : %02d : %02d "%(hour, minute, second,))
  time.sleep(1)
  second += 1
  if second == 60:
   minute += 1
   second -= 60
   if minute == 60:
      hour += 1
      minute -= 60

2 个答案:

答案 0 :(得分:1)

input 会一直阻塞,直到用户输入内容(然后按回车键)。
所以如果你把它放在你的 while 循环中,用户会被反复询问他是否想要停止,每次暂停时钟,这不是预期的。
但是如果你把 input 放在循环之外(你这样做很奇怪),那么在循环结束之前用户永远不会被要求输入一些东西(这永远不会)。
这意味着在您的情况下,input 不是解决方案。

有一个非常相似的问题,它有一个 accepted answer(稍微适合您的情况):

try:
    while True:
        print("%02d : %02d : %02d "%(hour, minute, second,))
        ...
except KeyboardInterrupt:
    # here the loop has definitely stopped
    ...

Ctrl+C 一起使用,是一种标准方式来通知程序停止某事。

如果您想使用除 Ctrl+C 以外的其他内容,StackOverflow 上还有其他可以满足您需求的问题:

因此,您的问题与其中一个问题重复。

答案 1 :(得分:0)

这是一个线程示例,可以执行您所描述的操作。

import time
import threading

thread_live = False

def countdown():
    seconds = 0;
    while thread_live:
        hour = seconds // 3600
        minute = (seconds // 60) % 60
        second = seconds % 60
        print("%02d:%02d:%02d "%(hour, minute, second))
        seconds += 1
        time.sleep(1)
    print("exiting")


while True:
    start = input("Press 1 to start and 2 to stop, 3 to exit: ")
    if start == "1" and not thread_live:
        cd = threading.Thread(target=countdown)
        thread_live = True
        cd.start()
    elif start == "2" and thread_live:
        thread_live = False
        cd.join()
    elif start == "3":
        break

这是一个使用 timedelta 来存储和格式化时间的版本:

import time
import datetime
import threading

thread_live = False

def countdown():
    t = datetime.timedelta(0)
    one = datetime.timedelta(seconds=1)

    while thread_live:
        print(str(t))
        t += one
        time.sleep(1)
    print("exiting")


while True:
    start = input("Press 1 to start and 2 to stop, 3 to exit: ")
    if start == "1" and not thread_live:
        cd = threading.Thread(target=countdown)
        thread_live = True
        cd.start()
    elif start == "2" and thread_live:
        thread_live = False
        cd.join()
    elif start == "3":
        break