我想创建一个打印循环:
"The train will leave at 13:36"
"The train will leave at 13:56"
"The train will leave at 14:16"
"The train will leave at 14:36"
"The train will leave at 14:56"
"The train will leave at 15:16"
etc. etc...
我有一个代码说:
h = 13
m = 36
for i in range(5):
print("The train will leave at {}:{} ".format(h,m))
m = m + 20
if 60 <= m:
break
print("The train will leave at {}:{} ".format(h,m))
h = h+1
m = m-60+20
输出为:
The train will leave at 13:36
The train will leave at 13:56
The train will leave at 14:16
The train will leave at 14:36
The train will leave at 15:-4
The train will leave at 15:16
The train will leave at 16:-24
The train will leave at 16:-4
The train will leave at 17:-44
The train will leave at 17:-24
我该如何解决它,使分钟数增加20分钟,每次达到60分钟,它应该输出正确的时间...
答案 0 :(得分:1)
使用binary arithmetic operations处理分钟和小时,即模运算符%
和楼层划分//
:
h = 13
m = 36
for i in range(10):
print("The train will leave at {}:{} ".format(h,m))
h = h+((m+20)//60)
m = (m+20)%60
if h == 24:
h = 0
请注意最后两行:您应该检查小时值,以便在h==24
时返回0。
答案 1 :(得分:1)
您可以使用标准库中的datetime
模块:
from datetime import timedelta, datetime
t = datetime(hour=13, minute=36, year=2019, month=6, day=9)
for i in range(5):
print("The train will leave at {}:{} ".format(t.hour,t.minute))
t += timedelta(minutes=20)
打印:
The train will leave at 13:36
The train will leave at 13:56
The train will leave at 14:16
The train will leave at 14:36
The train will leave at 14:56
答案 2 :(得分:0)
代码的略微修改版本。只需使用if
检查分钟。如果分钟数超过60,则将小时数增加一,然后减去60来倒回分钟数
h = 13
m = 36
for i in range(5):
if 60 <= m:
m = m-60
h = h+1
print("The train will leave at {}:{} ".format(h,m))
m = m + 20
# The train will leave at 13:36
# The train will leave at 13:56
# The train will leave at 14:16
# The train will leave at 14:36
# The train will leave at 14:56
答案 3 :(得分:0)
您应该尝试%运算符。
%
运算符是modulo operator,您可以轻松地将其视为提供左操作数与右操作数之间除法运算余数的运算符。 如果您在大学里做过一些群论或抽象代数,则定义此运算符的技巧可能会更多。
基本上从给定的分钟开始,然后增加20分钟。只要分钟数超过60分钟,我们就需要增加小时数。但是我们需要重置分钟数。因此,m
首次达到76时,我们将其重新设置为76 - (1 * 60) = 16
。请注意,m
永远不会超过120,除非从get go开始将其设置为大于99的数字。
我想你真正想要的是这个
h = 13
m = 36
for i in range(5):
print("The train will leave at {}:{} ".format(h,m))
m = m + 20
if m >= 60:
h += 1
m = m % 60
输出
# The train will leave at 13:36
# The train will leave at 13:56
# The train will leave at 14:16
# The train will leave at 14:36
# The train will leave at 14:56
但是您可能还应该考虑h
何时超过24。所以if h >= 24: h = 0
。
再次假设您始终以低于60的m开始。
答案 4 :(得分:0)
使用以下if语句检查小时更改,我更改了小时和分钟以进行重复检查
h = 15
m = 53
for i in range(5):
print("The train will leave at {}:{} ".format(h,m))
m = m + 20
if m >= 60:
h = h+1
m-=60
print("The train will leave at {}:{} ".format(h,m))
m = m + 20
执行将是:
The train will leave at 15:53
The train will leave at 16:13
The train will leave at 16:33
The train will leave at 16:53
The train will leave at 17:13
The train will leave at 17:33
The train will leave at 17:53
The train will leave at 18:13