我该如何退还所有费用的总和?

时间:2014-06-01 00:45:59

标签: python

所以,我一直在做代码学院。我有一项任务,说我需要返回以前函数的总和。我怎么做,因为这种方式不起作用?我如何避免将来遇到这个问题?

def hotel_cost(nights)
    nights = raw_input("How many nights are you staying? ")
    if nights == 0:
            return 0
    elif nights > 0:
        return 140 * nights

def plane_ride_cost(city):
    if city == "Charlotte":
        cost = 183
    elif city == "Tampa":
        cost = 220
    elif city == "Pittsburgh":
        cost = 222
    elif city == "Los Angeles":
        cost = 475
    return cost

def rental_car_cost(days):
    days = nights
    cost = days * 40
    if days >= 7:
        cost -= 50
    elif days >= 3:
        cost -= 20
    return cost

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

我收到此错误:

hotel_cost(1) raised an error:
invalid literal for int() with base 10

3 个答案:

答案 0 :(得分:1)

nights = raw_input("How many nights are you staying? ")

raw_input返回一个字符串,需要将其转换为整数。使用int(nights)

int()文档

答案 1 :(得分:1)

试试这个:

nights = input("How many nights are you staying? ")

input()返回一个int

我认为如果你避免在函数中获取用户输入会更好,在这种特殊情况下你可以收集外部函数中的所有信息,例如:

if __name__ == '__main__':
    days = input('Something..')
    nights = input('Something...')
    city = raw_input('Something...')
    # do whatever you want with data
    print  plane_ride_cost(city) + rental_car_cost(days) + hotel_cost(nights)

不知道你使用这个例子的方式......

你可以阅读input()

答案 2 :(得分:0)

如果您只想要整数作为输入,请更改以下行:

nights = raw_input("How many nights are you staying? ")

要:

nights = int(raw_input("How many nights are you staying? "))

这将通过将int()投射到您的raw_input()来修复错误,>>> x = raw_input() 98 >>> type(x) <type 'str'> >>> x = int(raw_input()) 23 >>> type(x) <type 'int'> >>> 会返回一个字符串。

{{1}}
相关问题