TypeError:不支持的操作数类型 - :'str'和'str'5

时间:2014-10-13 16:10:19

标签: python-3.x

这是一个只测试分配和用户输入的小程序,但我遇到了一些问题:

cars = input ("number of cars:")
space_in_a_car = 4.0
drivers = input ("number of drivers:")
passengers = input ("number of passengers:")
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven


print ("there are", cars, "cars available.")
print ("there are only", drivers, "drivers available.")
print ("there will be", cars_not_driven, "empty cars today.")
print ("we can transport", cars_not_driven, "people today.")
print ("we have", passengers, "to carpool today.")
print ("we need to put about", average_passengers_per_car, "in each car.")

当我运行该程序时,我得到了这个:

number of cars:100
number of drivers:30
number of passengers:90
Traceback (most recent call last):
  File "C:\Users\Owner\src\finplay\cars program.py", line 5, in <module>
    cars_not_driven = cars - drivers
TypeError: unsupported operand type(s) for -: 'str' and 'str'

我似乎无法弄清楚为什么会发生这种情况,我们将非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

简单回答:你不能从字符串中取出一个字符串。当您希望用户输入数字而不是使用cars = input("Number of cars: ")时使用cars = int(input("Number of cars: "))。否则它会接收文本,而不是数字,有点像要求Python从汽车或狗的猫中减去司机。