Functions
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 …
… Return…
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.
Example
Create a function that returns true if the value passed to it is even
def spread (n):if n% 2 == 0:return true
else:
return False
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.
Example
print (“parameter 1”, p, “parameter 2”, p2)
this function can be used
function (1,2)
or only with the first parameter
function (1)
in this case the second parameter will use the default value.
Internal functions
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