A function
is a piece of code that has been written some time before it is being used.
Some of these already come with python just as the case of the “Random”
function that has been used in the following example:
These
functions can be created by the programmer in the same code in which he/she
will be using it.
To create a
function we need to start defining it. To define it we write “def” followed by
the name of the function and the parameters that will be used in this between parentheses.
The next
line of code needs to be indented as this is what the function is supposed to
do. This function will print the primary colors:
If we try
to run this program, this is what will happen:
As you can
see, this program does not print anything. The reason for this is that we have successfully
created a function; however, we never called it. So this program knows that it
has to print “Red, Blue and Yellow” at some point, it just doesn´t know when.
So we need
when we want the function to be called. In this case the function will be
called if the following condition is true:
Note that the
line in which we state the condition is not intended. This means that this like
and what is followed by it is no longer part of the function we called “Colors”.
In this
program, the user is asked if he/she wants to know which are the primary colors
and it receives an input in the form of a string. If the string it received is “yes”,
then the function is called. This is what will happen if the conditions stated
below are true:
This is another
example of a created function. This function has an argument called “x”. This
argument is the name of a person. The function outputs the text “My name is”
followed by the value given to "x".
Before
calling the function we need to define what will be the value of “x”. After
that, we call the function by typing the name of the function followed by
parentheses.
After running it, this is what will happen:
We can also
change what the function will print by changing what is being witten between
the parentheses. For example, if instead of typing “name(x)” we type “name(x*4)”.
The
argument this function will be taking as “x” is not “Frida”; it is “Frida”*4,
which is “FridaFridaFridaFrida”. This is what will happen:
Another way
to create a function is the one shown below:
The
variable “stars” was defined inside the function; however, it can only be used
inside the function. For printing variables that were defined inside the
function we need to type “return” followed by the name of the variable at the
end of the function.
This way,
the program can use the variable correctly even if it is inside a function:
As you can
see, this program asks the user for a number, then it print the same quantity
of “*” that the user stated.
If we
decide to omit the “return” part, the result will be totally different:
No hay comentarios:
Publicar un comentario