Marcus Burkhart
Marcus Burkhart

Reputation: 93

Python NameError: not defined

I am trying to create an accumulating total based on users input.

class Accumulator:
    # Create self value == 0
    def __init__(self, newval = 0):
        self.value = newval

    # Addition function
    def add(self, newval):
        return self.value + newval

Then I have several different functions that go here. After the functions are all complete I set my operator equal to anything other that 'T' which instantly terminates the program. Here when i try: newval, operator is where I get my first error, secondly I will get the error "add" is not defined.

operator = 'z'

while operator != 't' or operator != 'T':
    try:
        newval, operator
    except:
        #Prompt user to enter a number and valid operator
        newval, operator = input("Enter a valid number, space, then an operator: ").split()

Below here, depending on what the users inputs for the operator calls whatever function associated with the letter. Take "A" for example:

elif operator == 'a' or operator == 'A':
        print(add(self, newval))
        self.value = add(self, newval)

Then My program should keep the accumulating total and continue running... untill the user enters 't' or 'T'.

Upvotes: 2

Views: 1754

Answers (1)

Neel
Neel

Reputation: 21315

You have to use self.add if you are using inside class

elif operator == 'a' or operator == 'A':
    print(self.add(self, newval))
    self.value = self.add(self, newval)

If you are not using inside same class then you have to use object varibale

a = Accumulator()
...
...
elif operator == 'a' or operator == 'A':
    print(a.add(self, newval))
    self.value = a.add(self, newval)

Upvotes: 1

Related Questions