-5
 def some_func():

     print("Hi!")

 var = some_func()

      print(var)

My question is, why var does not return "Hi!" IF that already was defined when I write def some_func(): print("Hi!")

Can someone clarify it to me?

abhi
  • 1,712
  • 1
  • 19
  • 35
diegotco
  • 25
  • 5
  • 6
    because print prints. and return returns. and you never wrote a return. – Paritosh Singh Feb 03 '19 at 16:24
  • 1
    Welcome! In python printing is different from returning. Your code will output "Hi!" to the console, but return None. If you want `var` to equal "Hi!" you should `return "Hi!"` – beenjaminnn Feb 03 '19 at 16:25

3 Answers3

0

Use return "Hi!!" instead of print("Hi!!") "Hi!!" will go to the place from where the function is called.

0

In Python, if there is a need for a function to return a value, the return keyword must be used:

def some_func():
    return "Hi!"

var = some_func()

print(var)

This will now actually print Hi! when calling print(var). In the original question, if the code is left as-is, all that will be printed is the following:

Hi!
None

To get a bit more detailed, what's happening is that some_func() is called when running the statement var = some_func(); this will print Hi! as we see above, but since some_func() doesn't return anything, var is set to None.

This is why on the second line, when calling print(var), None is printed instead of Hi!.

For more information on None: What is a None value?

abhi
  • 1,712
  • 1
  • 19
  • 35
0

You're missing the return statement in your function, meaning that when your function is called nothing is returned to the caller.

Do this:

def foo():
    return "Hello"

var = foo()
print(var)
Employee
  • 2,841
  • 3
  • 25
  • 48