Why sum(self.angle1,self.angle2,self.angle3) gives error?


#1



https://www.codecademy.com/en/courses/python-intermediate-en-WL8e4/3/2?curriculum_id=4f89dab3d788890003000096#


The below code is correct but just one thing that I didn't understand is that why in the if statement the sum() function provide error but adding the variables using + doesn't provide error?? Please read the comment in the code..


@mtf @leonhard.wettengmx.n


class Triangle(object):
    def __init__(self,angle1,angle2,angle3):
        self.angle1 = angle1
        self.angle2 = angle2
        self.angle3 = angle3

    number_of_sides = 3
    
    def check_angles(self):
        if self.angle1+self.angle2+self.angle3==180:     #if sum(self.angle1,self.angle2,self.angle3)==180: gives an error.. Why??
            return True
        return False


#2

@oonyx
From
https://docs.python.org/2/library/functions.html
you can read
https://docs.python.org/2/library/functions.html#sum
in which it is stated
that you can use the sum() function
like
sum([1,2,3])


#3

Thank You sir :blush:


#4

What error were you getting? The code looks and runs as expected.

To add to what Leon wrote,

    def check_angles(self):
        return sum([self.angle1, self,angle2, self.angle3])

#5
def check_angles(self):
    return sum([self.angle1, self,angle2, self.angle3])

This code worked..
Earlier it was not passing when I used the code:

def check_angles(self):
    return sum(self.angle1, self,angle2, self.angle3)

This was the error I was getting:
Oops, try again. Make sure to pass self as an argument to your check_angles method!

Then I found out that the following code was also not working, there was some problem with sum that I didn't know..

print sum(10,20)

After leon's help I understood what my mistake was..
The following code worked then..

print sum([10,20])

#6

We can also sum() a tuple...

    print (sum((30,60,90)))     # 180

#7

:smiley: That's nice.. I have so much to learn right now.. :grin: Thanks..


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.