0

I am trying to understand Classes in python.

Question: Why I am getting None in the output?

Here is my code :

class Student:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def show_student(self):
        print("Student Name:", self.name)
        print("Student Age: ", self.age)


first_student = Student("amit", 12)
print(first_student.show_student())

And here is the output.

C:\Python38\python.exe D:/LearningRoot/DirFirst/test.py
Student Name: amit
Student Age:  12
None
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
amitsuneja
  • 23
  • 1
  • 3
  • Because `first_student.show_student()` *returns `None`*, and you print the return value of `first_student.show_student()` – juanpa.arrivillaga Dec 12 '21 at 07:39
  • This has *nothing to do with* classes. You can equally well cause the same problem with ordinary functions. You should make sure you understand those fundamentals before moving on. – Karl Knechtel Dec 12 '21 at 07:44

1 Answers1

1

first_student.show_student() returns None, which is what all Python functions return if no explicit return value was specified. Therefore:

print(first_student.show_student())

This will evaluate to print(None).

rb612
  • 5,280
  • 3
  • 30
  • 68
  • "first_student.show_student() does not return anything." - it *does* return something. It returns `None`, like all functions that don't have an explicit return value. – Thierry Lathuille Dec 12 '21 at 07:41
  • @ThierryLathuille Indeed, I misspoke here, thanks for the correction. Edited the answer accordingly. – rb612 Dec 12 '21 at 07:43