Python中不支持的操作数类型

时间:2014-07-10 13:43:46

标签: 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 个答案:

答案 0 :(得分:3)

您应该将string类型原始输入转换为数字类型(floatint);

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

答案 1 :(得分:1)

函数raw_input()会将输入的值作为字符串返回,因此您必须将其转换为数字(intfloat):

quantity = int(raw_input("How many products did you buy?"))
cost = float(raw_input("How much did you pay?"))