我正在创建一个运行时计算器,并且无法使用函数

时间:2014-10-09 06:06:16

标签: python

这是我目前的代码:

  def get_input():
        pace = str(input("Enter pace [mm:ss]: "))
        distance = float(input("Enter distance [miles]: "))
        mm, ss = int(pace.split(":")[0]), int(pace.split(":")[1])
        return(pace, distance, mm, ss)
    def calculate_time(pace, distance, mm, ss):
        print(pace)
        print(mm)
        print(ss)
        new_sec = mm * 60 
        full_sec = ss + new_sec
        print(full_sec)
        print(distance)
        total_time_sec = full_sec * distance
        print(total_time_sec)
        seconds_per_mile = total_time_sec / 60
        hours = int(seconds_per_mile // 60)
        print(seconds_per_mile)
        print(hours)
        minutes = int((total_time_sec - (hours * 3600))//60)
        print(minutes)
        seconds = int(total_time_sec - ((hours * 3600) + (minutes * 60)))
        print(seconds)
        print(pace, full_sec, distance)
        return(seconds, minutes, hours)
    def display_time(pace, distance, mm, ss, seconds, minutes, hours):
        if seconds < 10:
            print(hours,":",minutes,":0",seconds, sep="")
        else:
            print(hours,":",minutes,":",seconds, sep="")
        return()
    def main():
        pace, distance, mm, ss = get_input()
        new_sec, full_sec, total_time_sec, seconds_per_mile, hours, minutes, seconds = calculate_time(pace, distance, mm, ss)
        display_time(pace, distance, mm, ss, seconds, minutes, hours)
    main()

我不擅长使用功能。我不相信我对任何东西的回归都有充分的理解。

这是我得到的错误:

Traceback (most recent call last):
  File "C:/Python33/homework 3 test.py", line 36, in <module>
    main()
  File "C:/Python33/homework 3 test.py", line 34, in main
    new_sec, full_sec, total_time_sec, seconds_per_mile, hours, minutes, seconds = calculate_time(pace, distance, mm, ss)
ValueError: need more than 3 values to unpack

该功能的目的是让用户输入他们的步速和距离,并输出运行距离所需的时间。

例如:

Enter pace [mm:ss]: 8:15
Enter distance [miles]: 26.2
3:36:09

如果有人能解释我做错了什么,我会非常感激。我不一定想知道如何对待发球台,但我遇到了很多麻烦,需要一点助力。

1 个答案:

答案 0 :(得分:1)

您的代码有点难以阅读(请查看PEP-8 (Style Guide for Python code)),但您的函数calculate_time()的一个明显问题是它确实存在

return(seconds, minutes, hours)   # return a three-element tuple

但是main()试图将其解压缩为六个变量:

new_sec, full_sec, total_time_sec, seconds_per_mile, hours, minutes, seconds = calculate_time(pace, distance, mm, ss)

一些意见:

pace = str(input("Enter pace [mm:ss]: "))
mm, ss = int(pace.split(":")[0]), int(pace.split(":")[1])

过于复杂。 input()已经返回字符串,并且您可以在此处使用一个名为list comprehension的漂亮Python功能:

pace = input("Enter pace [mm:ss]: ")
mm, ss = [int(item) for item in pace.split(":")]