So I've only just started learning python and needed some help with my code. Here is my code,
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'
I was supposed to have it return more than one amount of time, but just didn't know how to write it in such a way. For instance, it was suppose to return conversions for 4014, 4074, 4112, and so forth. I've been told that functions, classes, tuples, and lists are the way to go, but just don't know where to begin. Are there any tips?
As already pointed out, you can convert you code by simply using a for
loop, iterating over the input values arranged in a list
, like:
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")
Additionally, you could make a function
that performs the calculation/print and the use that one:
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)
There are additional things that can be improved: the function could be done such that printing is left to the main code path, and the function just returns a tuple
of computed values:
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")