convert 函数有什么问题?

问题描述 投票:0回答:2
def main():
    askForTime = input("What time is it? ").strip().split()
    time = convert(askForTime)
    if 7 <= time <= 8:
        print("breacfast time")
    elif 12 <= time <= 13:
        print("lunch time")
    elif 18 <= time <= 19:
        print("dinner time")



def convert(clock):
    if "p.m" in clock or "pm" in clock:
        hours, minutes = clock[0].split(":")
        timer = (float(hours) + 12) + (float(minutes) / 60)
        return timer
    else:
        hours, minutes = clock[0].split(":")
        timer = float(hours) + (float(minutes) / 60)
        return timer


if __name__ == "__main__":
    main()
convert successfully returns decimal hours
    expected "7.5", not "Error\n"

我检查了我的程序,转换函数确实产生了十进制小时。 有人可以向我解释一下我缺少什么吗?

python type-conversion decimal cs50
2个回答
0
投票

检查从这一行获得的

askForTime
值:

def main():
    askForTime = input("What time is it? ").strip().split()

当你这样做时,你会发现它以列表的形式返回输入。 (那是因为您使用了

.split()
- 返回的是一个列表。)您的
convert()
函数“有效”,因为它需要一个列表。但是,
check50
通过使用字符串调用进行测试,如下所示:

pset_1/meal/SO_74635140/ $ python
>>> from meal import convert
>>> print(convert("7:30"))

当您如上所示运行时,您将收到此错误消息:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/workspaces/68927141/pset_1/meal/SO_74635140/meal.py", line 19, in convert
    hours, minutes = clock[0].split(":")
ValueError: not enough values to unpack (expected 2, got 1)

此外,您将“早餐时间”错误地拼写为“早餐时间”。一旦你解决了第一个问题,这将导致另一个

check50
错误。


0
投票

实际上,问题在于我们在函数之外编写代码。系统要求我们在函数内编写/管理所有代码,以便我们尽可能地学习函数的概念。所以我这样做了,我只是在函数中编写了所有代码,我的工作就完成了。 感谢所有在这里写信并提出问题并尝试回答的人。保持祝福。

© www.soinside.com 2019 - 2024. All rights reserved.