error while writing python class to calculate sum of two numbers

I write this code in python:

class Jam():
def __init__(self,a,b):
    self.a=a
    self.b=b      
def majmoo(self):
    return self.a+ self.b
numbers= Jam(10,55)
print(numbers.majmoo())
        

But it doesn't run and give this error:

NameError: name 'Jam' is not defined

I dont know why it gives this error I defined Jam() in first line but It say it is not defined. How should I fix this?

3 answers

  • answered 2020-06-27 03:58 Ghost

    Indentation problem. You did not indent the code inside the class. It should be like this:

    class Jam():
        def __init__(self,a,b):
            self.a=a
            self.b=b      
        def majmoo(self):
            return self.a+ self.b
    numbers= Jam(10,55)
    print(numbers.majmoo())
            
    

  • answered 2020-06-27 04:03 Carolina Coronado Alderete

    Your code is ok. I think your problem is that your code is

    class Jam():
    def __init__(self,a,b):
        self.a=a
        self.b=b      
    def majmoo(self):
        return self.a+ self.b
    numbers= Jam(10,55)
    print(numbers.majmoo())
    

    all on the same line. Try this:

    class Jam():
      def __init__(self,a,b):
          self.a=a
          self.b=b      
      def majmoo(self):
          return self.a+ self.b
    numbers= Jam(10,55)
    print(numbers.majmoo())
            
        
    

  • answered 2020-06-27 04:14 kheem

    You should take care of indentation. It is true that there is no braces unlike other programming languages. But indentation plays an important role. In your program, the class and its methods are in same indentation that's why python compiler thinks they belong to same group that's why you are getting error. To avoid error, right shift these methods(tab) and run again your program.