CS1-FULL-FALL2021
Maíra Marques Samary
maira.
Functions
A software program can be VERY VERY
BIG.
Is it feasible to create gigantic programs,
with thousands or millions of lines of code
in a single Python code file?
?
Clearly not.
A program that grows in a single file
becomes difficult to modify, expand and
maintain.
Even writing a small program we may
realize that it is natural to divide a program
into sub-programs.
Let’s think of how to write a program that
can calculate the factorial of a number
n!
Too start, basic combinatory rules:
If we have a set of n elements, in how many
ways can we choose k elements?
?
We have to calculate three factorials and the
three are calculated in the same way.
!
To not repeat the same calculation three
times, we can create a function (a
“subprocess”) to calculate the factorial.
!
input data == parameters
output data == return value
!
In Python when we are thinking about a
sub process in our program we are thinking
about a function.
!
def
To create a function, in Python the following reserved
word is used:
def function_name():
#Function code
?
This function have parameters and return values?
How do we make a function to run (execute)?
?
function_name(parameters)
Parameters can be a list of values / variables, separated by
a comma.
If the function does not require parameters, then nothing
is put between the parentheses.
Let’s write a function called factorial that
calculates n! and print the result
!
def factorial(n):
#Function code
?
The function has parameters?
Write a Python program that calculates them and
prints the values 1 !, 2 !, 3!, …, 12! using (calling /
invoking) the function that you have just written.
(Use While)
!
A function that generates output data should
in most cases deliver (return) data
!
Deliver => Return
!
Let’s discuss a know example:
Take 1
What’s up here with random.randint?
Are we using the result for something?
Take 2
And here? Do we use the result of random.randint (1,7) for something?..
No, we never invoke / call the function throw_a_dice.
Take 3
Here we are invoking throw_a_dice, but we do not do anything
with the value that is generated inside the function when calling
random.randint ()
Take 4
On line 9, the program calls throw_a_dice, and this
function prints the value obtained, between 1 and 6.
How do we now save the value of the dice in
a variable as a result of calling the function?
?
Take 5
We could try this, but it does not give the expected result. Why?
… the behavior is not what we expected because the function does
not return the value generated by random.randint (1,7)
How do we make a function return?
?