A function is a sequence of actions that perform an operation and that can be identified by a name.
The functions allow us
. have a more structured code
. avoid code repetition
. is the basis of structured programming
. can be reused with other programs
In Phyton we can create functions as follows
def function (.. list of parameters …):
… body of the function …
Parameter list and return value are optional.
There is no difference between functions (that return a value) and procedures (without a return value) as it exists in other types of languages.
Create a function that returns true if the value passed to it is even
Keep in mind that Python does not use blocks to delimit the code.
To define the body of the function, indentation is used.
Also indicate that the type of the parameters is not defined nor of the value that is returned, with this it is achieved that the same function can work for different types of data.
Functions with default parameters
Functions can be defined with default parameters, if the parameter is not indicated in the call, the default value of the function definition will be taken.
this function can be used
or only with the first parameter
in this case the second parameter will use the default value.
Python provides a number of predefined functions that can be used directly.
Some of these functions are
max (x, y) – get the maximum value
min (x, y) – get the minimum value
len (x) – get the number of characters in a string
Type conversion functions can also be used
int (“2”) – convert a string to an integer
str (22) – convert an integer to a string