我不知道我把事情搞砸了。我两天前刚开始使用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
试试这个:
解释一下:
raw_input
会给你一个字符串。 如果要对从原始输入得到的值进行算术运算,则需要将其转换为整数。你知道吗另外,如果您试图从命令行运行此命令,则需要下面两行。你知道吗
你真的应该替换:
def trip_cost(city, days)
与
def trip_cost()
因为您不是从传递到方法中的参数填充city和days值,而是使用原始输入从控制台获取这些值。你知道吗
如果你这样做了,那么改变:
trip_cost(None, None)
至
trip_cost()
所以说了这么多,我最终还是要重写它:
输出结果如下:
trip_cost()
忽略传递给它的参数。对它内部raw_input()
的调用返回字符串(在python2.x中),但是其他函数期望整数被传递给它们。改用input()
函数。你知道吗相关问题 更多 >
编程相关推荐