1
class student:
    birth_day = 21 
    birth_month = 4 
    birth_year = 1998 
    def __init__(self,name):
        self.naav = name 
    def SayHi(self):
        return print('hello'+''+self.naav)


Topper = student('vikas')
print(Topper.naav) 
print(Topper.SayHi())
print(student.birth_day)  
print(Topper.birth_day)  
#print(student.naav)

The output to this is

vikas
hellovikas
None
21
21

I am confused with third output "None",am not sure how it works ,somebody help me understand

Samdare
  • 11
  • 2
  • 1
    The `print` function always returns `None`. You can `return 'hello' + self.naav`, or you can `print('hello' + self.naav)`, but you can't have both. If you `return print('hello' + self.naav)`, then the `print` function will still be called and print to your IDE or the command shell, but it will return `None` because the `print` function returns `None`. – Joel Jul 25 '18 at 01:14
  • 1
    That's all true, but if you remove the `return` and just `print('hello'+''+self.naav)`, the function is _still_ going to return `None`, because that's the default value returned by any function that doesn't have a `return` statement. So the real issue is that you shouldn't be calling `print(Topper.SayHi())`. (What did you _want_ that to print?) – abarnert Jul 25 '18 at 01:17
  • The marked duplicate explains in general what happens when a function returns `None` and you try to `print` it or otherwise display it. I'm pretty sure there's another good dup about the fact that `print` itself returns `None`, which we should probably also add, but I can't find it… – abarnert Jul 25 '18 at 01:21
  • But maybe the second answer on that dup (by Dair) covers that? – abarnert Jul 25 '18 at 01:21

1 Answers1

1

This is happening because on print(Topper.SayHi()) you are printing what the function SayHi returns, which is nothing (None). This is because print('hello'+''+self.naav) doesn't return a value, it prints and returns nothing.

What you should do is return only the string, then print the return of the function SayHi (as you're already doing).

class student:
    ... 
    def SayHi(self):
        return 'hello' + self.naav

...
print(Topper.SayHi())
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Visckmart
  • 111
  • 1