-1

i just learnt classes in python programming (learning still) and started experimenting with it and found my code gives a none statement in output but didn't use any return in my functions

MY CODE


class GreetingMessage:
    def welcome_message(self):
        print("you are welcome to python")
    def thank_you_message(self):
        print("Ok Bye Thank You")
    def on_process_message(self):
        print("process is on progress")
        

msg1 = GreetingMessage()

print(msg1.welcome_message())
print(msg1.on_process_message())
print(msg1.thank_you_message())

OUTPUT:

you are welcome to python None process is on progress None Ok Bye Thank You None

thebjorn
  • 26,297
  • 11
  • 96
  • 138
  • Functions return None by default, even if you don’t include a return statement. – jkr Oct 10 '21 at 12:08
  • You are printing the return values of your functions in the last 3 lines. They don't have a return function so it prints "none". Either remove the prints around those functions calls, or make the functions return a string to print and not print by themselves. – Rani Sharim Oct 10 '21 at 12:09
  • I hope this helps: https://stackoverflow.com/a/15300671/2681662 – MSH Oct 10 '21 at 12:15

2 Answers2

1

If you don't use a return function in your code, it will automatically return None. However, you aren't obligated to print the result of the function you are using, if it already prints by itself. You can just write instead :

msg1.welcome_message()
msg1.on_process_message()
msg1.thank_you_message()
0

A function will return None automatically until and unless you've written a return statement. If you have written print statement, then no need to write print again outside the class. Just call the method

msg1.welcome_message()
msg1.on_process_message()
msg1.thank_you_message()

If at all you want a return statement, then you'll have to write print outside the class while calling the method

Edited code would be:

class GreetingMessage:
    def welcome_message(self):
        return "you are welcome to python"
    def thank_you_message(self):
        return "Ok Bye Thank You"
    def on_process_message(self):
        return "process is on progress"
    

msg1 = GreetingMessage()

print(msg1.welcome_message())
print(msg1.on_process_message())
print(msg1.thank_you_message())