Not as you imagine - any command that ends with :
in Python creates a block - and this block has to have expressions and commands, otherwise it is a syntax error.
Updating:
pass functions as parameter, as described below, except in specialized languages called "functional" can be considered a little advanced. For those who are learning the basics of a mainly imperative language, like Python, the best thing is that your function does all the tests that can be as complicated as you want, and returns a value True or False - you make a if
at the point where it calls the function and tests its return - especially if it wants to change local variables.
(this is the main idea in the reply of Maniero, who wrote independent of my original answer, which continues below)
When we don’t want to do anything in the block (for example, sometimes in a except:
, for a crash that we know can happen and is not something essential), there is the command pass
, that just doesn’t do anything.
However, in Python, functions are objects like any other, and can be passed as parameters. Then you can do something like what you want by passing as parameter to the first function a second function that makes the desired action.
def if_(x, func):
if x>6:
return func(x)
return None
def imprime(x):
print(x)
def x_quadrado(x):
return x ** 2
x = int(input("Valor de x"))
if_(x, imprime)
x = input("Valor de x")
quadrado = if_(x, x_quadrado)
print(quadrado)
Note that in this case, as we are not calling the fuções "prints" and "x_square" when calling the function, we do not use parentheses after its name: Python treats the functions exactly as it treats any variable.
Within the function, the second parameter has the name func
and will receive the past function. Only when we func(...)
is that the function is actually called.
Also, for very short tasks, there is the keyword lambda
which allows you to write "mini-functions" in a single line of code, within an expression. A function created with lambda does not need to have a name in a variable and can be declared direct in the call to the first function. Lambdas do not need the "Return" command: they have a single expression and their result is that it is returned. So you can write like this:
if_(x, lambda x: print(x))
But this form sometimes decreases readability - in most cases the recommended is to create another function with def
even.
Thanks for the reply. Return false in filter(p) is required?
– user93774