The definition of a function specifies exactly how a function is constructed, what parameters are passed to it, and what value it returns to the calling function.
With the declaration we name a variable and make it known to the compiler.
Definition and declaration differ in some points. The definition includes a memory allocation for the function, while no memory is allocated in the declaration. The declaration can be done several times, vice versa a function can be defined exactly once in a program.
In Python, functions are defined with the keyword def
followed by the function name and the input parameters.
def function_name():
# code to be executed
def function_name(parameter_1 = default_value, parameter_2 = default_value, ...):
# code to be executed
def add():
# code to be executed
def add(a = 3, b = 5):
return a + b
This code defines a function named add
that takes two optional arguments, a
and b
, both with default values of 3
and 5
, respectively. The function adds the two arguments together and returns the result using the return
statement.
Here’s an example of how you could use this function:
print(add()) # 8
print(add(a=4)) # 9
print(add(b=6)) # 9
print(add(a=7, b=8)) # 15
In the first call to the function, both a
and b
are set to their default values of 3
and 5
, respectively. The function returns 3 + 5 = 8
.
In the second call to the function, a
is set to 4
while b
is set to its default value of 5
. The function returns 4 + 5 = 9
.
In the third call to the function, b
is set to 6
while a
is set to its default value of 3
. The function returns 3 + 6 = 9
.
In the fourth call to the function, both a
and b
are set to 7
and 8
, respectively. The function returns 7 + 8 = 15
.