Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中不支持的操作数类型_Python - Fatal编程技术网

Python中不支持的操作数类型

Python中不支持的操作数类型,python,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

我编写了一个非常简单的脚本来获取产品数量、成本和购买的平均值:

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'
回溯(最近一次呼叫最后一次):
文件“purchase.py”,第9行,在
平均值=数量/成本
TypeError:/:“str”和“str”的操作数类型不受支持

您应该将
字符串
类型原始输入转换为数字类型(
float
int


您应该将
string
type原始输入转换为数字类型(
float
int


函数
raw\u input()
将以字符串形式返回输入的值,因此必须将其转换为数字(
int
float
):


函数
raw\u input()
将以字符串形式返回输入的值,因此必须将其转换为数字(
int
float
):


您应该将str-type原始输入转换为int-type。您应该将str-type原始输入转换为int-type。可能需要进行一些数据验证为什么要导入future division?感谢您提供的快速解决方案。Future division似乎确实没有必要,您可能想加入一些数据验证为什么要导入Future division?感谢您提供的快速解决方案。在这里,未来的分裂似乎确实没有必要
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
quantity = int(raw_input("How many products did you buy?"))
cost = float(raw_input("How much did you pay?"))