【问题标题】:Traceback (most recent call last): and TypeError:Traceback(最近一次通话最后一次):和 TypeError:
【发布时间】:2018-06-10 19:09:46
【问题描述】:

我仍然是 Python 的初学者,目前正在使用 codecademy。我决定将其中一个练习程序稍微复杂化,我遇到了这个错误:

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'

这是我的代码:

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)

任何帮助将不胜感激,谢谢!我是初学者,所以我的 python 术语有点生疏。

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    您正在执行days - 1cost -= 50dayscost 是用户输入,因此是一个字符串(在您的情况下更准确的unicode 字符串),您应该在执行任何操作之前转换为int(尤其是数学),因为这是你的意图:

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

    这是因为您将它们当作数字来使用而不进行转换

    但是请注意,输入除数字以外的任何内容都会产生错误,但这是另一个问题的主题

    【讨论】:

    • 只是对 R.Palmer 这个答案的补充:您还应该考虑使用 try...except-blocks 进行用户输入。您可能想要处理无法转换为 int 的字符串,例如“九”或完全不同的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    相关资源
    最近更新 更多