Not as you are imagining - any command that ends with :
in Python creates a block - and that block must have expressions and commands, otherwise it is a syntax error.
Update :
passing functions as a parameter, as I describe below, except in specialized languages called "functional" can be considered somewhat advanced. For those who are learning the basics of a primarily imperative language, such as Python, its best to do all the tests that can be as complicated as you want, and return a value of True or False - you do if
in point at which you call the function and test its return - especially if you want to change local variables.
(this is the main idea in Maniero's reply, which he wrote independently of my original answer, which continues below)
When we do not want to do anything in the block (for example, sometimes in a except:
, for a file that we know can happen and is not essential), there is the command pass
, which simply does nothing. / p>
However, in Python, functions are objects like any other, and can be passed as parameters. So you can do something like what you want by passing as a parameter to the first function a second function that does 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, since we are not calling the "print" and "x_quadrado" functions at the time of calling the function, we do not use parentheses after its name: Python treats functions exactly as it treats any variable.
Within the function, the second parameter is named func
and will receive the last function. Only when we do func(...)
does the function actually call.
In addition, for very short tasks, there is the keyword lambda
that allows you to write "mini-functions" in a single line of code, within an expression. A function created with lambda need not have a name in a variable and can be declared direct in the first function call. 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 what is recommended is to create another function with def
itself.