Function Returns | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Function Returns

Can someone explain why the output to this code is a 6? def func(x): return x+1 f = func print(f(2) + func(2)) Im still learning and math isn’t my strongest subject

14th Jul 2020, 9:40 PM
Marie
3 Answers
+ 4
Marie func(2) return 2+1=3 So print(func(2)) is 3 and print(func(2)+func(2)) is print(3+3). 3+3=6
14th Jul 2020, 9:53 PM
Petr
+ 2
func is a python function... Functions may have one or more parameters, that are passed, when the function gets called... Here, x is a parameter, that is passed to func. Furthermore, functions always have a return value, that they give back, when finished (this return value may be none). Here the return value is x + 1.. Now you reference f to func, which means, func can now be called as f as well... So when you call f, the same function gets called as if you were calling func.. So when you call f or func, both with x = 2, both will return 2 + 1 = 3, and 3 + 3 = 6... Hope this makes it clearer...
14th Jul 2020, 9:56 PM
G B
G B - avatar
+ 1
func() takes a number and returns that number +1 the variable f refers the the func() function (so its the same, just shorter to write) print(f(2) + func(2)) print(3 + func(2)) print(3 + 3) print(6) # 6
14th Jul 2020, 9:56 PM
Slick
Slick - avatar