Python Forum

Full Version: Everything works except for one line of code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm learning classes in Python and I've written a program that outputs the value of two integer variables. And I want to include a method that sums them. Everything works (the program successfully outputs the value of x and the value of y okay. But in the final print statement where I'm saying where I want to output the text and then call the function (in the print statement) to add the two together is where it's going wrong.

I'm not getting any specific error messages other than a "not listening" message.

Here is my program:
class SumTheIntegers:
    def __init__(self):
        self.x = 10
        self.y = 13

def sum_integers():
    sum = x + y
    return sum
    
def main():
    SumIntegers = SumTheIntegers()
    
    print("The value of x is", SumIntegers.x)
    print("The value of y is", SumIntegers.y)
    print()
    print("The sum is", SumIntegers.sum_integers())
    
main()
You need to look a little bit more into python oop

class SumTheIntegers:
    def __init__(self, x, y):
        self.x = x
        self.y = y
 
    def _sum(self):
        return self.x + self.y
     
def main():
    sum_integers = SumTheIntegers(10, 13)
     
    print("The value of x is", sum_integers.x)
    print("The value of y is", sum_integers.y)
    print()
    print("The sum is", sum_integers._sum())
     
main()
  • def sum_integers(): should be indented into the class and should have self as a first parameter.
  • sum = x + y x &y need self. in front of them

class SumTheIntegers:
    def __init__(self):
        self.x = 10
        self.y = 13
 
    def sum_integers(self):
        sum = self.x + self.y
        return sum
     
def main():
    sum_integers = SumTheIntegers()
     
    print("The value of x is", sum_integers.x)
    print("The value of y is", sum_integers.y)
    print()
    print("The sum is", sum_integers.sum_integers())
     
main()
(Sep-06-2019, 05:57 PM)ThomasL Wrote: [ -> ]You need to look a little bit more into python oop

class SumTheIntegers:
    def __init__(self, x, y):
        self.x = x
        self.y = y
 
    def _sum(self):
        return self.x + self.y
     
def main():
    sum_integers = SumTheIntegers(10, 13)
     
    print("The value of x is", sum_integers.x)
    print("The value of y is", sum_integers.y)
    print()
    print("The sum is", sum_integers._sum())
     
main()

You are totally not helpful in your reply. That's like someone asking you on the road to help you with their flat tire and you tell them "You need to learn a little more about tires". And then you drive away.