这个程序工作得很好,但是在每个if语句中必须重复time =“%s:%s”%(小时,分钟)。我把它放在所有其他的范围和地方,但我无法弄清楚为什么必须重复它,而不是在if语句或任何其他位置之外声明它。
def minutesToHours():
hour = 0
entry = input("How many minutes? I will convert it to hours...")
if 0 <= entry < 60:
minute = entry
time = "%s:%s" % (hour, minute)
print time
elif entry >= 60:
hour = entry / 60
minute = entry % 60
time = "%s:%s" % (hour, minute)
print time
else:
print "Please enter a number greater than zero next time."
minutesToHours()
input()
答案 0 :(得分:3)
您首先不需要if
语句:
hour, minute = divmod(int(entry), 60)
time = "%s:%s" % (hour, minute)
甚至:
time = "%s:%s" % divmod(int(entry), 60)
这是divmod文档
答案 1 :(得分:1)
您可能想要重构一些代码。
entry
不是号码。if
语句,因为计算模数与大于60的entry
相同。您可以使用divmod
进行除法和模数。提出所有这些建议:
def minutesToHours():
entry = ""
while not entry.isdigit():
if entry != "":
print "Please enter a number greater than zero next time."
entry = input("How many minutes? I will convert it to hours...")
hour, minutes = divmod(int(entry), 60)
time = "%s:%s" % (hour, minutes)
print time
minutesToHours()
input()
答案 2 :(得分:0)
因为hour
在entry
之后使用{{1}},所以{{1}}不存在。
答案 3 :(得分:0)
你可以使用lambda
def minutesToHours():
time = lambda hour, minute: '%s: %s' % (hour, minute)
hour = 0
entry = input("How many minutes? I will convert it to hours...")
if 0 <= entry < 60:
minute = entry
elif entry >= 60:
hour = entry / 60
minute = entry % 60
else:
print "Please enter a number greater than zero next time."
return
print time(hour, minute)
答案 4 :(得分:0)
def minutesToHours():
entry = input("How many minutes? I will convert it to hours...")
if entry < 0:
print "Please enter a number greater than zero next time."
else:
print "%02d:%02d" % divmod(entry,60)
minutesToHours()
input()