Python旅游费用('匹兹堡', 4)引发错误:强制转换为Unicode:需要字符串或缓冲区,找到int

2024-10-02 16:26:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道我把事情搞砸了。我两天前刚开始使用Python,这是我的问题所在。你知道吗

错误

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

Tags: tocityreturnifdefdayshotelcost
2条回答

试试这个:

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会给你一个字符串。 如果要对从原始输入得到的值进行算术运算,则需要将其转换为整数。你知道吗

另外,如果您试图从命令行运行此命令,则需要下面两行。你知道吗

你真的应该替换:

def trip_cost(city, days)

def trip_cost()

因为您不是从传递到方法中的参数填充city和days值,而是使用原始输入从控制台获取这些值。你知道吗

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

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

trip_cost()忽略传递给它的参数。对它内部raw_input()的调用返回字符串(在python2.x中),但是其他函数期望整数被传递给它们。改用input()函数。你知道吗

相关问题 更多 >