Click here to Skip to main content
16,020,249 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i need a little help, why does when i try to print "total" it says that "total is not defined"

def total(self):
        sum=0
        for elem in self:
            sum=sum+elem
        return sum


must calculate the total sum of the list values

Python
class BillBatch:
    def __init__(self,list_of_bills):
        self.list_of_bills=list_of_bills

    def __len__(self):
        return len(self.list_of_bills)
    
    def total(self):
        sum=0
        for elem in self:
            sum=sum+elem
        return sum
        

    def __getitem__(self,index):
        return self.list_of_bills[index]



values = [10, 20, 50, 100] 
   
print("The number of Bills in the batch: ", len(values)) 

print(total(values))


What I have tried:

i tried the code cleanly with no class and it works, i'm definitely not doing something right.
Posted
Updated 19-Jul-22 8:30am

Because total is a function that is defined as part of the BillBatch class and requires an instance of the class in order to be called.
Start here: Python Classes[^]
 
Share this answer
 
Comments
Maciej Los 19-Jul-22 13:23pm    
5ed!
Change the final line of code to :
Python
batch = BillBatch(values)
print('Total bills:', batch.total())
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900