我正在学习如何用Python编程并且坚持这个简单的练习。我将下面的代码保存到一个文件test.py并使用“python test.py”从我的OSX命令行运行它并继续收到我无法理解的错误消息。我猜这个错误是一个被忽视的相当明显的事情:P
错误消息在代码后面:
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):
total = 40 * days
if days >= 7:
total = total - 50
elif days >= 3:
total = total - 20
return total
def trip_cost(city, days, spending_money):
return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city) +
spending_money
thecity = raw_input("What city will you visit? ")
thedays = raw_input("How many days will you be traveling? ")
thespending_money = raw_input("How much spending money will you have? ")
trip_cost(thecity, thedays, thespending_money)
控制台错误消息:
$ python test.py
What city will you visit? Los Angeles
How many days will you be traveling? 5
How much spending money will you have? 600
Traceback (most recent call last):
File "test.py", line 29, in <module>
trip_cost(thecity, thedays, thespending_money)
File "test.py", line 23, in trip_cost
return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city) + spending_money
File "test.py", line 17, in rental_car_cost
total = total - 50
TypeError: unsupported operand type(s) for -: 'str' and 'int'
答案 0 :(得分:1)
将thedays = raw_input("How many days will you be traveling? ")
更改为thedays = input("How many days will you be traveling? ")
,并在需要数字值时将所有其他raw_input
替换为input
。
答案 1 :(得分:1)
thecity = raw_input("What city will you visit? ")
&#34;城市n#34;是一个字符串。使用int
:
thecity = int(raw_input("What city will you visit? "))
与其他输入类似。
答案 2 :(得分:0)
thedays = raw_input("How many days will you be traveling? ")
raw_input
返回一个字符串。因此,当您输入5
时,您会获得字符串 '5'
而不是整数 5
。当您尝试添加Python时,Python不会自动为您转换这些内容,因为在某些情况下,这会导致更大的意外。相反,它希望您明确地进行转换,以便在任何输入的情况下,您的代码始终是明确的(例如,“将字符串'abc'解析为基本10整数”是总是错误;尝试通过隐式转换执行"abc" + 5
可能会决定将5转换为字符串'5'并进行字符串连接以提供"abc5"
)。
执行此操作的方法是使用内置int
,它接受一个字符串并返回一个从中解析的整数:
thedays = int(raw_input("How many days will you be traveling? "))