0
Please explain this "simple" code
this code has 4 lines, 1st is the definition of the function then three lines follow as statements for what this function does. def func1(x): print(x) print("this line is printed") return 3*x 1) in the python shell, if I call the func1(4) the output is: 4 this line is printed 12 2) in the python shell, if I assign to a variable f = func1(4) the output is: 4 this line is printed I don't understand why the two lines are executed despite the fact that the variable f is just a box to which I assigned the func1 object, but I didn't give the instruction print(f). 3) then... must mysterious of all... if I type print(f) the output is 12 !!?!? why??
3 Answers
+ 3
1) in python shell is printed result of statement also, for this you get printed x, "this line is printed" and the result of func1(4) call (12)
2) Here you call func1(4) then the function IS EXECUTED (then x and "this line is printed" will be printed)
3) because f is not a function but its a var that contain func1(4) call result, thats 12
Try to change
f= func1
and you will see
+ 1
thank you for your reply, but...
2) Here you call func1(4) then the function IS EXECUTED (then x and "this line is printed" will be printed)
since the function is executed, why its third line is not executed? I mean why I do not see the execution of third line as an output besides the first two lines only?
3) because f is not a function but its a var that con tain func1(4) call result, thats 12
if I'm correct... so the var f is being assigned a function which result is only the line with command return, the third one only, so why the lines with print are bypassed ?
Try to change
f= func1
I tried that but it deviates from my core question... or simply I haven't understood nothing about functions and 'return' command
+ 1
You have wrong, third line, the return statement, is executed. For this that "f" will contain 12 (the result of func1(4) ). Dont mix print output with execution. In shell mode, you will get "automatic" print when the line that you insert, give some value but in script mode, they will not printed if you dont use the print function.
Futhermore gived a function "f" remember that with f() you call it (then you execute it) and return a result if any returned from f, but using only f (without () ) you giving the function reference.. example:
def mul(a, b):
return a*b
v1= mul(10,2)
v2= mul
v3= v2(30,4)
v1 will contain the result return by calling mul with 10 and 2 (20).
v2 will contain a reference to mul function then you can use v2 like mul
v3 will contain the result returned by v2 that it same than mul (thats a function), with params 30 and 4 (then 120)