所以我刚开始学习python并需要一些代码帮助。这是我的代码,
x = 4014
minute = x / 60
whole_minute = round(minute, 0)
if whole_minute * 60 <= x:
sec_1 = x - (whole_minute * 60)
print("%.0f" % whole_minute, "minutes and", "%.0f" % sec_1, "seconds")
else:
better_whole_minute = whole_minute - 1
sec_2 = x - (better_whole_minute * 60)
print("%.0f" % better_whole_minute, "minutes and", "%.0f" % sec_2, "seconds")
# it prints '66 minutes and 54 seconds'
我应该让它返回超过一个时间,但只是不知道如何以这种方式写它。例如,假设返回4014,4074,4112等的转换。我被告知功能,类,元组和列表是可行的方法,但只是不知道从哪里开始。有没有提示?
答案 0 :(得分:0)
您需要使用for
循环迭代它:
time_list = [4014, 4074, 4112] # list holding all values of `x`
for x in time_list:
# ... your code from after you initialize value of `x`
这将为列表
中出现的x
的所有值运行代码
答案 1 :(得分:0)
正如已经指出的那样,您可以通过简单地使用for
循环来转换代码,迭代list
中排列的输入值,如:
time_list = [4014, 4074, 4112]
for x in time_list:
minute = x / 60
whole_minute = round(minute, 0)
if whole_minute * 60 <= x:
sec_1 = x - (whole_minute * 60)
print("%.0f" % whole_minute, "minutes and", "%.0f" % sec_1, "seconds")
else:
better_whole_minute = whole_minute - 1
sec_2 = x - (better_whole_minute * 60)
print("%.0f" % better_whole_minute, "minutes and", "%.0f" % sec_2, "seconds")
此外,你可以制作一个执行计算/打印的function
并使用那个:
def calculate_time(x):
minute = x / 60
whole_minute = round(minute, 0)
if whole_minute * 60 <= x:
sec_1 = x - (whole_minute * 60)
print("%.0f" % whole_minute, "minutes and", "%.0f" % sec_1, "seconds")
else:
better_whole_minute = whole_minute - 1
sec_2 = x - (better_whole_minute * 60)
print("%.0f" % better_whole_minute, "minutes and", "%.0f" % sec_2, "seconds")
time_list = [4014, 4074, 4112]
for x in time_list:
calculate_time(x)
还有其他一些方法可以改进:可以完成这个功能,使打印留在主代码路径中,而函数只返回tuple
个计算值:
def calculate_time(x):
minute = x / 60
whole_minute = round(minute, 0)
if whole_minute * 60 <= x:
sec_1 = x - (whole_minute * 60)
return (whole_minute, sec_1)
else:
better_whole_minute = whole_minute - 1
sec_2 = x - (better_whole_minute * 60)
return (better_whole_minute, sec_2)
time_list = [4014, 4074, 4112]
for x in time_list:
minutes, seconds = calculate_time(x)
print("%.0f" % minutes, "minutes and", "%.0f" % seconds, "seconds")