ubuntu2004
Functions III - returning values
Returning values from a function
Programmers rarely use functions to print to the screen as the print()
function already does that for us. Normally functions are used to do something to the argument that is passed to it then return the result of that something.
Consider the len()
function:
In this code we pass a DNA sequence as a string to len()
which returns its length which we can assign to a variable, in this case called seq_len
.
This is a more versatile use of functions than just printing because we can now use the value of seq_len
for other purposes.
In the following code is a function called square_it()
that takes a number, squares it and returns the square.
The function square_it()
takes a number and stores it in the parameter x
. x
is squared (remember **
is the power operator, i.e., x
to the power 2 is x squared.). The square of x
is assigned to the variable square
. Finally, the function returns the value in square
back to the main program where it is assigned to the variable y
, and then printed.
Functions can return any type of variable
In the last example our function returned a float. But a function can return any type of variable: a string, a list, a dictionary.
The following code takes a list of DNA sequences and returns a list of their lengths.
Functions can return more than one value
The above function returned just a single value, but functions can return as many values as we like.
The function count_purines_pyrimidines()
in the following code takes a DNA sequence and returns the number of purines (A and G) and the number of pyrimidines (C and T).
The function returns both values stored in the variables purines
and pyrimidines
simultaneously back to the main program.