[英]Can't multiply sequence by non-int of type 'float' in Python
I have the following code in python: 我在python中有以下代码:
class TotalCost:
#constructor
def __init__(self, quantity, size):
self.__quantity=quantity
self.__size=size
self.__cost=0.0
self.__total=0.0
def DetermineCost(self):
#determine cost per unit
if self.__size=="A":
self.__cost=2.29
elif self.__size=="B":
self.__cost=3.50
elif self.__size=="C":
self.__cost=4.95
elif self.__size=="D":
self.__cost=7.00
elif self.__size=="E":
self.__cost=9.95
def DetermineTotal(self): #calculate total
self.__total= self.__cost * self.__quantity
def GetCost(self):
return self.__cost
def GetTotal(self):
return self.__total
def Menu(self):
print("----------------SIZES/PRICES----------------")
print(" Size A = $2.92")
print(" Size B = $3.50")
print(" Size C = $4.95")
print(" Size D = $7.00")
print(" Size E = $9.95")
print("--------------------------------------------")
def main():
again=""
print("Prices:")
while again!="no":
size=""
quantity=0
display="" #i put this variable only because it wont go without it and idk what else to do>.<
TotalCost.Menu(display)
while size!="A" and size!="B" and size!="C" and size!="D" and size!="E":
size=str(input("Which size? Please enter A,B,C,D, or E. : "))
quantity=int(input("How many of this size? : "))
while quantity<0:
quantity=int(input("How many of this size? : "))
Calc=TotalCost(size, quantity)
Calc.DetermineCost()
Calc.DetermineTotal()
print("--------------------------------------------")
print("Your order:")
print("Size: " , size)
print("Quantity: " , quantity)
print("Cost each: $" , Calc.GetCost()) print("Total cost: $", Calc.GetTotal())
main()
I receive the following error when I execute this code: 执行此代码时收到以下错误:
File "C:/Python33/halpmeanon.py", line 21, in DetermineTotal self._ total= self. 文件“C:/Python33/halpmeanon.py”,第21行,在DetermineTotal self._ total = self中。 _cost * self.__quantity TypeError: can't multiply sequence by non-int of type 'float' _cost * self .__ quantity TypeError:不能将序列乘以'float'类型的非int
This program is supposed to ask for a letter(size) & quantity, determine cost per unit by given letter, and calculate/output total cost. 该程序应该询问字母(大小)和数量,确定给定字母的每单位成本,以及计算/输出总成本。
How can I resolve this error in my code? 如何在我的代码中解决此错误?
You got the order of arguments the wrong way round in 你得到了错误的参数顺序
Calc=TotalCost(size, quantity)
Your constructor is: 你的构造函数是:
def __init__(self, quantity, size):
A great way to code so you can make sure that doesn't happen is to name your arguments when calling a method: 一种很好的编码方式,这样你可以确保不会发生这种情况是在调用方法时命名你的参数:
Instead of: 代替:
Calc=TotalCost(size, quantity)
Do this: 做这个:
Calc=TotalCost(size=size, quantity=quantity) # or TotalCost(quantity=quantity, size=size)
That way you can give the arguments out of order and not have to worry about bugs like the one you encountered. 这样你可以不按顺序给出参数,而不必担心你遇到的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.