【问题标题】:End whileloop using python shell使用 python shell 结束 whileloop
【发布时间】:2016-03-08 02:41:14
【问题描述】:

我一直在尝试制作一个秒表,我的同龄人向我提出了挑战,但我希望它能够在我在 python shell 中输入某个键时停止计时器。

import time

timer = 0
timeTrueFalse = True

startTimer = input("Type start if you want to start!")

if (startTimer == "start"):
    while timeTrueFalse:
            timer = (timer + 1)
            print (timer)
            time.sleep(1)

【问题讨论】:

  • 任何键还是特定键?按下 Control+C 会引发 KeyboardInterrupt,您可以捕捉到它。此外,if 语句中不需要括号。 if startTimer == "start": 可以正常工作;-)
  • @Carpetsmoker:使用 Ctrl+C 的想法很好。我没想到。
  • 阅读本文。那里也有几个链接可能会对您有所帮助。 stackoverflow.com/questions/14400806/…

标签: python


【解决方案1】:

您可以使用时间戳

import time

while not str(raw_input("write start: ")) == "start" :
    pass

tstamp=time.time()

while not str(raw_input("write stop: ")) == "stop" :
    pass    

delta=time.time()-tstamp

#delta has the time in seconds.

【讨论】:

  • "但我希望它能够在我在 python shell 中输入某个键时停止计时器"
  • 所以你把退出验证放在增量线之前。可以使用系统定时器就不需要睡眠
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 2015-03-04
  • 2020-04-14
  • 2011-01-15
  • 1970-01-01
  • 2014-12-01
相关资源
最近更新 更多