你怎么不用试一下就用键盘中断

2024-03-29 05:06:47 发布

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

我想为我刚找到工作的弟弟做一个基本的工资计时器。。。我想要的是一个while循环运行代码,等待有人按enter键(或其他键)结束循环并给出当前工资。我希望键盘打断,但如果有一个更简单的方法来做这件事,我很乐意听到它。我怎么能这么做?你知道吗


Tags: 方法代码键盘计时器enterwhile乐意弟弟
1条回答
网友
1楼 · 发布于 2024-03-29 05:06:47

只有当有人按ctrl-C或类似键时,才会生成键盘中断。你知道吗

听起来你的计划是要有这样的代码:

from time import sleep

wage = 0
try:
    while True:
        wage = wage + hourly_rate
        sleep(60 * 60)  # an hour in seconds
except KeyboardInterrupt:
    print('you earned', wage)

然后有人按ctrl-C?这将与try/except一起工作。但是如果你想让某人按回车键,那么不要把事情累加起来,而是做一些数学计算:

from time import time

start = time()  # time in seconds from some arbitrary date in 1970 (it's a standard)
input('hit return to get your wage!')
end = time()
elapsed = end - start  # time that has passed in seconds between start and end
wage = hourly_rate * elapsed / (60 * 60)  # convert from hourly
print('you earned', wage)

第一个版本是有点乐观,因为它增加了每一个小时开始。第二个更准确。你知道吗

恭喜你哥哥!你知道吗

相关问题 更多 >