我写了一个非常简单的脚本来获取购买的产品数量,成本和平均值:
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'
答案 0 :(得分: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
答案 1 :(得分:1)
函数raw_input()
会将输入的值作为字符串返回,因此您必须将其转换为数字(int
或float
):
quantity = int(raw_input("How many products did you buy?"))
cost = float(raw_input("How much did you pay?"))