Reputation: 15
I am trying to learn classes and I don't understand why my code is printing "none"?
CODE
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print("Hello my name is " + self.name +" and I am "+ str(self.age) +" years old.")
def crazy_talk(self):
print(self.name +" says I'm a test")
p1 = Person("John", 36)
p2 = Person("Bob", 23)
p3 = Person("Joe", 3)
p4 = Person("John", 17)
p5 = Person("Ronald", 102)
p6 = Person("Kevin", 55)
p7 = Person("Albert", 70)
people_list=[p1,p2,p3,p4,p5,p6,p7]
for human in people_list:<br>
print human.introduce()
OUTPUT
Hello my name is John and I am 36 years old.
None
Hello my name is Bob and I am 23 years old.
None
Hello my name is Joe and I am 3 years old.
None
Hello my name is John and I am 17 years old.
None
Hello my name is Ronald and I am 102 years old.
None
Hello my name is Kevin and I am 55 years old.
None
Hello my name is Albert and I am 70 years old.
None
Upvotes: 0
Views: 1000
Reputation: 988
So, that expression human.introduce()
, it doesn't return anything.
def introduce(self):
print("Hello my name is " + self.name +" and I am "+ str(self.age) +" years old.")
This method definition says that, when called, that string will be printed out, but it does not actually return any value to the caller of the method, hence None
.
So here, where you call the method
for human in people_list:
print human.introduce()
For every human you call the method which will print out the string, and then the method will implicitly return None
to the caller. This None
is what the print
inside of the for loop receives.
If you want the call to human.introduce()
to return a string that can be printed, then you can change it to this
def introduce(self):
return "Hello my name is " + self.name +" and I am "+ str(self.age) +" years old."
Which will not perform the side effect of printing the string, but it will return the string to the caller.
(Also for your own good, please transition to learning python 3 if at all possible. Python 2.7 is more than a decade old and is no longer supported)
Upvotes: 1
Reputation: 22042
This happens because on your last line you are printing out the return value of calling the human.introduce()
method. This is always None
. The introduce
method itself prints out the the introduction text, but then returns no return value.
To fix, change your last line to just human.introduce()
. Or alternatively, change your introduce()
method to return (but not print) the text, and then print the result of calling the introduce()
method on your last line.
Upvotes: 1