分钟转换器和返回 Python 中的多个值

Minute Converter & Returning Multiple Values in Python

所以我才刚刚开始学习 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'

我本来应该 return 不止一次,但就是不知道怎么写成这样。例如,假设 4014、4074、4112 等的 return 转换。有人告诉我函数、类、元组和列表是可行的方法,但我不知道从哪里开始。有什么攻略吗?

您需要使用 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 的所有值的代码

正如已经指出的那样,您可以通过简单地使用 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 来执行 calculation/print 并使用那个:

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)

还有其他可以改进的地方:可以完成该功能,以便将打印留给主代码路径,并且该功能只是 returns 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")