我正在做codecademy的Python,在计划假期作业时遇到了麻烦(7/7)。你知道吗
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
elif city == 'Los Angeles':
return 475
def rental_car_cost(days):
cost = days*40
if days >= 7:
cost -= 50
elif days >= 3 and days <7:
cost -= 20
return cost
def trip_cost(city,days,spending_money):
return rental_car_cost(days)+hotel_cost(days - 1)+plane_ride_cost(city)+spending_money
city = raw_input('city?')
days = raw_input('days?')
spending_money = raw_input('money?')
print trip_cost(city,days,spending_money)
当我运行脚本并在提示符处输入时,它失败,并显示以下错误:
Traceback (most recent call last):
File "python", line 28, in <module>
File "python", line 23, in trip_cost
File "python", line 17, in rental_car_cost
TypeError: unsupported operand type(s) for -=: 'unicode' and 'int'
这里有一些问题,但是首先,如果你的赋值允许,我会使用一个类而不是多个函数。我只需要创建一个大对象。原因是您有太多的参数,所以将参数传递给类,然后允许函数对其进行操作比将参数传递给多个函数更有意义。一切都是相似的,因为它都与旅行有关,所以我把它存储在一个类中。我使用的是Python3.6,因此它与您使用的Python2版本略有不同,但是您可以看到,我仍然需要将用户输入转换为整数值。在代码中,您不是将用户输入转换为整数值,而是尝试对数据执行数学运算。这也会给你一个回溯。您必须在原始输入之前定义数据类型。输入函数在Python2中的工作方式不会像在Python3.6中那样。但是,如果您曾经用Java编写过代码,它本质上就像声明一个变量。另外,在这里获取用户输入时,我会更改cities,以使用.lower()方法计算值。信任用户是有风险的。我在这里做了一些其他的改变,希望能有所帮助。你知道吗
以下是您的输出:
raw_input
返回一个字符串,不能用字符串进行数学运算。您需要将适当的值转换为数字,例如:相关问题 更多 >
编程相关推荐