【问题标题】:adding multiple function together new to python将多个函数添加到 python 中
【发布时间】:2013-08-07 02:04:12
【问题描述】:

所以我在 codeacademy 上 Python 教程时遇到了这个问题
代码是这样的

def hotel_cost(days):
    return days*140

Charlotte = "Charlotte"
Tampa = "Tampa"
Pittsburgh = "Pittsburgh"
LosAngeles = "Los Angeles"


def plane_ride_cost(city):
    if city == Charlotte:
        return 183
    elif city == Tampa:
        return 220
    elif city == Pittsburgh:
        return 222
    elif city ==LosAngeles:
        return 475
    else:
        return "not"

def rental_car_cost(days):
    if days <3:
       return days*40
    if days >=3 and days<7:
       return days*40-20
    if days >=7:
        return days*40-50

def trip_cost(city,days):
    return hotel_cost(days)+rental_car_cost(days)+plane_ride_cost(city)

我再次意识到语法中的错误

def trip_cost(city,days):
    return hotel_cost(days)+rental_car_cost(days)+plane_ride_cost(city)

但我没有足够的知识以任何可能的方式修改它(我确实尝试过)

非常感谢所有查看此内容的人

【问题讨论】:

    标签: python function syntax


    【解决方案1】:

    我复制粘贴了你的代码,一切正常,但没有输出。

    所以这没有什么让你认为你的代码有问题吗?

    只需在最后添加这一行:

    print trip_cost('Tampa', 10)
    

    你会看到输出

    你可以写一堆prints 和raw_inputs 让用户输入城市和日期。

    编辑

    哦,我没有注意到 plane_ride_cost(city) 的错误默认返回,只需将其更改为 0 或者当您的用户输入错误的城市时其他有意义的东西。

    【讨论】:

    • 回溯(最近一次调用最后):文件“”,第 34 行,在 文件“”,第 31 行,在 trip_cost 文件“”,行2、在hotel_cost NameError: global name 'nights' is not defined
    • 它给了我这种错误:(你能多看看它吗谢谢你的努力
    • 如何在上面的代码中使用 raw_input 我似乎无法让它像这样工作? nights = raw_input("enter:") print hotel_cost(raw_iput)
    • 您使用raw_input() 从用户输入中获取一个值,然后将其传递给您的函数。请在此处查看文档:docs.python.org/2/library/functions.html#raw_input
    • 这是我无法访问的值,例如我添加了 a=raw_input("-") print hotel_cost(a) 它为我提供了我输入的数字的重复版本,我阅读了你给我的链接并没有发现它对我很有帮助:(请灌输我:)
    【解决方案2】:

    以下函数存在问题。您返回 not 而不是返回整数。然后,您尝试在 trip_cost 方法中添加返回值。这将无法正常工作。考虑返回一个 0 而不是 not 然后一切就可以正常工作了

    def plane_ride_cost(city):
        if city == Charlotte:
            return 183
        elif city == Tampa:
            return 220
        elif city == Pittsburgh:
            return 222
        elif city ==LosAngeles:
            return 475
        else:
            return "not"  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-12
      • 2014-09-18
      • 2023-03-29
      • 1970-01-01
      • 2012-04-13
      • 1970-01-01
      • 2021-11-24
      • 2011-04-11
      相关资源
      最近更新 更多