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
3 Respostas
+ 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
+ 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...
+ 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