PYTHON trip_cost('Pittsburgh',4)引发了一个错误:强制转换为Unicode:需要字符串或缓冲区,找到int

时间:2015-08-03 23:57:01

标签: python unicode

我看不出我搞砸了。我刚刚在2天前启动了Python,这是来自Codecademy的问题。

错误

trip_cost('Pittsburgh', 4) raised an error: coercing to Unicode: need string or buffer, int found

代码

def hotel_cost(nights):
    return 140 * nights

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

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

def trip_cost(city, days):
    city = raw_input("What city are you travelling to?")
    days = raw_input("How many days are you staying?")
    total_cost = hotel_cost(days) + plane_ride_cost(city) + rental_car_cost(days)
    print total_cost

2 个答案:

答案 0 :(得分:2)

trip_cost()忽略传递给它的参数。对其中的raw_input()的调用返回字符串(在Python 2.x中),但是您的其他函数期望将整数传递给它们。请改用input()功能。

答案 1 :(得分:1)

试试这个:

def hotel_cost(nights):
    return 140 * nights

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

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

def trip_cost(city, days):
    city = raw_input("What city are you travelling to?")
    days = raw_input("How many days are you staying?")
    total_cost = hotel_cost(int(days)) + plane_ride_cost(city) + rental_car_cost(int(days))
    print total_cost

if __name__ == '__main__':
    trip_cost(None, None)

解释一下: raw_input会给你一个字符串。 如果您要对从raw_input获得的值进行算术运算,则需要将其转换为整数。

此外,如果您尝试从命令行运行此操作,则需要输入最后两行。

你真的应该替换:

def trip_cost(city, days)

def trip_cost()

因为您没有从传递给方法的参数中填充city和days值,而是使用raw_input从控制台获取这些值。

如果你这样做,那么改变:

trip_cost(None, None)

trip_cost()

所有这些都说,这就是我最终会重写它的方式:

def hotel_cost(nights):
    return 140 * nights

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

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

def trip_cost():
    city = raw_input("What city are you travelling to?")
    days = raw_input("How many days are you staying?")
    total_cost = hotel_cost(int(days)) + plane_ride_cost(city) + rental_car_cost(int(days))
    print total_cost

if __name__ == '__main__':
    trip_cost()

输出如下:

(cost)macbook:cost joeyoung$ python cost.py 
What city are you travelling to?Pittsburgh
How many days are you staying?4
922