0
def myfunc():
    print("hello")

b=myfunc()

In the above code the output is "hello" just by assigning b to myfunc(). Why is this? I never asked for myfunc() to be executed, I just assigned name to it. I know classes are executed on import, but this isn't a class.

user3124200
  • 343
  • 1
  • 5
  • What the code does is to assign the return value of `myfunc()` to b. In assignments, the right value is assigned to the left variable. So this causes the function to be executed. – amitr Mar 11 '19 at 05:20
  • If `myfunc()` doesn’t call a function, then what does…? – deceze Mar 11 '19 at 06:37

3 Answers3

1

myfunc and myfunc() are not the same thing. In your code, myfunc is a function reference while myfunc() returns the results from calling myfunc.

You want this instead:

b=myfunc
Ouroborus
  • 16,237
  • 4
  • 39
  • 62
0

myfunc() means you are making call to the function, since function is not returning b is not getting any value.

if you print b is showing nothing.

if you assign b=myfunc in this case you are passing the reference of function to variable b if you use b() it will execute function body it means b and myfunc will point to same reference.

Pradeep Pandey
  • 307
  • 2
  • 7
0

As there is a difference between print a value or returning something from the function. You are just printing in the function and not returning any value from the function. So if the function is not returning anything, that can't be assigned to the variable... executing the function with myfunc() will only print the value to the terminal.. In case you want to store the value to a variable, you need to return it from the function. :)

def myfunc():
    print("Helloo")

b = myfunc()
--> hellloo

b = myfunc
b
--> <function __main__.hello()>

b()
--> hellloo

def myfucn():
    return("hellloo") 

b = hello()
b
--> hellloo'
Siddhant Kaushal
  • 385
  • 1
  • 3
  • 13