Search code examples
python-3.xoopmethodsnonetype

Python: Method to increment by one returns None


Due to lack of experience I cannot find the error in my code. I have two methods defined and both return None when I call them. Here's my code:

class User:
def __init__(self, fname, lname, age):
    self.fname = fname
    self.lname = lname
    self.age = age
    self.login_attempts = 0

def describe_user(self):
    print("The user's name is {} {} and he or she is {} old".format(self.fname, self.lname, self.age))

def greet_user(self):
    print(f"Hello {self.fname}!")

def increment_login_attempts(self):
    self.login_attempts += 1

def reset_login_attempts(self):
    self.login_attempts = 0


user1 = User("Rita", "Jones", 19)
user1.describe_user()
user1.greet_user()
print("")
user2 = User("Ben", "Holmes", 26)
user2.describe_user()
user2.greet_user()
print(user2.increment_login_attempts())
print(user2.increment_login_attempts())
print(user2.increment_login_attempts())
print(user2.reset_login_attempts())

The last four print None


Solution

  • Any method or function which does not end with an explicit return statement (or ends with an explicit plain return or return None) returns None by default. If you want to return the new value, just add:

    return self.login_attempts
    

    as appropriate.