XuMuK XuMuK - 1 month ago 6
Python Question

Python function which will be applied to another variable

For example:

def some_function(a):
if a == 1:
return x ** 2
else:
return x - 1000

some_function(a)(b)


And as result when we have
a==1
, obtain
b**2
and in all other cases
b-1000
.

Is it even possible in python, to get as return some unknown variable, which will be replaced by another?

The question is exactly about not touching
b
, it will be unreachable for function directly.

And the code which should work is
some_function(a)(b)
.

Answer

The other answer is correct in this case, but may not be suitable for what you are trying to do.

What you are trying to do is return a function, which Python makes extremely easy:

def some_function(a):
    if a == 1:
        def f(x):
            return x ** 2
    else:
        def f(x):
            return x - 1000
    return f

>>> some_function(1)(5)
25
>>> some_function(0)(1500)
500