分钟转换器&在Python中返回多个值

时间:2016-11-29 20:13:54

标签: python python-3.x multiple-variable-return

所以我刚开始学习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等的转换。我被告知功能,类,元组和列表是可行的方法,但只是不知道从哪里开始。有没有提示?

2 个答案:

答案 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")