简体   繁体   English

追溯(最近一次呼叫过去):和TypeError:

[英]Traceback (most recent call last): and TypeError:

I'm still very much a beginner with Python and I'm using codecademy at the minute. 我仍然是Python的初学者,目前正在使用codecademy。 I decided to complicate one of the practice programs slightly and I've come across this error: 我决定稍微简化其中一个练习程序,但遇到了这个错误:

Traceback (most recent call last):
File "python", line 30, in <module>
File "python", line 24, in trip_cost
File "python", line 18, in rental_car_cost
TypeError: unsupported operand type(s) for -: 'unicode' and 'int'

Here is my code: 这是我的代码:

def hotel_cost(nights):
  # the hotel costs $140 per night
  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

x = raw_input("Where are you going? ")
y = raw_input("How many days are you going for? ")
z = raw_input("How much spending money are you taking? ")

print trip_cost(x, y, z)

Any help would be much appreciated, thanks! 任何帮助将不胜感激,谢谢! I'm a beginner so my python lingo is a bit rusty. 我是一个初学者,所以我的python术语有点生锈。

You're doing days - 1 or cost -= 50 but days and cost are user inputs and therefore a string (unicode string more accurately in your case), you should convert to int before doing anything (especially math) since that's your intention: 您正在做days - 1cost -= 50但是dayscost是用户输入,因此是一个字符串(在您的情况下,unicode字符串更准确),您应该在执行任何操作(尤其是数学运算)之前将其转换为int ,因为这是您的意图:

y = int(raw_input("How many days are you going for? "))
z = int(raw_input("How much spending money are you taking? "))

This is because you are using them as if they're numbers without converting 这是因为您将它们当作数字使用,而没有转换

However be warned, inputting in anything other then numbers will generate errors, but that's the subject for another question 但是请注意,输入数字以外的任何数字都会产生错误,但这是另一个问题的主题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM