循环加20分钟直到17:16

2024-04-28 22:13:06 发布

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

我要打印代码: 火车明天13:36发车 . . 火车明天17:16开 火车每20分钟开一次

这是我迄今为止所尝试的

h = 13
m = 36
i = 20
while(True):
    m = m + i
    if m >= 60:
        h = h + 1 and m = 0
        if h > 17 and m > 16:
            break
        print("The train will leave at {0:0d}:{1:0d} tomorrow".format(h, m))

当运行代码时,我得到“SyntaxError:cannotassigntooperator” 我做错什么了


Tags: andthe代码trueformatiftrainwill
2条回答

不要试图用这种天真的方式与时间共事。有那么多的用例和边缘案例需要考虑和处理

使用适当的时间对象(在本例中是datetime,因为是纯的^{} objects do no support ^{} calculations

from datetime import datetime, timedelta

current_time = datetime.now().replace(hour=13, minute=16)
end_time = datetime.now().replace(hour=17, minute=16)
delta_minutes = 20

while current_time <= end_time:
    print("The train will leave at {} tomorrow".format(current_time.strftime('%H:%M')))
    current_time += timedelta(minutes=delta_minutes)

输出

The train will leave at 13:16 tomorrow
The train will leave at 13:36 tomorrow
The train will leave at 13:56 tomorrow
The train will leave at 14:16 tomorrow
The train will leave at 14:36 tomorrow
The train will leave at 14:56 tomorrow
The train will leave at 15:16 tomorrow
The train will leave at 15:36 tomorrow
The train will leave at 15:56 tomorrow
The train will leave at 16:16 tomorrow
The train will leave at 16:36 tomorrow
The train will leave at 16:56 tomorrow
The train will leave at 17:16 tomorrow

导致这个错误的问题是h=h+1 and m=0,如果您想在一行中执行此操作,您可以执行h, m = h + 1, m,尽管我个人会将它拆分为两行

除此之外,还有一些其他问题:

  1. if h>17 and m>16:上的缩进错误。只有在 m是第一个>= 60,因为m被重置为0,而m永远不会是>16,所以while循环将永远运行

    通过以下方式解决此问题:

    if m>=60:
        h=h+1
        m=0
    if h>17 and m>16:
        break
    
  2. 因为你重置了m=0,以后再也不会是1616 -> 36 -> 56 -> 76 -> 0 -> 20 -> 40 -> 60 -> 0 -> ...m=m-60超过60

    时,可以通过重置m=m-60来解决这个问题

最终的脚本将类似于:

h = 13
m = 36
i = 20
while(True):
    m=m+i
    if m>=60:
        h=h+1
        m=m-60
    if h>17 and m>16:
        break
    print("The train will leave at {0:0d}:{1:0d} tomorrow".format(h, m))

相关问题 更多 >