在Python中不能将sequence乘以'float'类型的nonit

2024-10-03 09:20:20 发布

您现在位置: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()  

执行此代码时收到以下错误:

File "C:/Python33/halpmeanon.py", line 21, in DetermineTotal self._total= self._cost * self.__quantity TypeError: can't multiply sequence by non-int of type 'float'

上下文

该程序要求输入字母(大小)和数量,根据给定字母确定单位成本,并计算/输出总成本。在

如何解决代码中的此错误?在


Tags: and代码selfsizedefcalcquantitytotal
1条回答
网友
1楼 · 发布于 2024-10-03 09:20:20

你把争论的顺序弄错了

Calc=TotalCost(size, quantity)  

您的构造函数是:

^{pr2}$

编写代码以确保不会发生这种情况的一个好方法是在调用方法时命名参数:

而不是:

Calc=TotalCost(size, quantity)

这样做:

Calc=TotalCost(size=size, quantity=quantity) # or TotalCost(quantity=quantity, size=size)

这样你就可以给出无序的参数,而不必担心你遇到的那种错误。在

相关问题 更多 >