Python中的不支持操作数类型
我写了一个非常简单的脚本,用来获取购买的产品数量、成本和平均值:
from __future__ import division
def print_purchase(arg1, arg2, arg3):
print """You bought %r products and paid %r,
for an average of %d""" % (arg1, arg2, arg3)
quantity = raw_input("How many products did you buy?")
cost = raw_input("How much did you pay?")
average = quantity/cost
print_purchase(quantity, cost, average)
这个脚本运行得很好,直到需要进行除法运算的时候。我尝试了几种方法来“修改”代码,以便它可以进行这些运算(比如导入除法功能等等),但我还是没能让它正常工作:
Traceback (most recent call last):
File "purchase.py", line 9, in <module>
average = quantity/cost
TypeError: unsupported operand type(s) for /: 'str' and 'str'
2 个回答
1
函数 raw_input()
会把你输入的内容当作一个 字符串 返回,所以你需要把它转换成数字(可以是 int
整数或者 float
浮点数):
quantity = int(raw_input("How many products did you buy?"))
cost = float(raw_input("How much did you pay?"))
3
你应该把输入的文本类型(string
)转换成数字类型(float
或 int
);
from __future__ import division
def print_purchase(arg1, arg2, arg3):
print """You bought %r products and paid %r,
for an average of %d""" % (arg1, arg2, arg3)
try:
quantity = float(raw_input("How many products did you buy?"))
cost = float(raw_input("How much did you pay?"))
except (TypeError, ValueError):
print ("Not numeric. Try Again.")
print_purchase(quantity, cost, average)
average = quantity/cost