Functions#
Todo
Synchronize with Week4/01-fonctions.md; especially the MySTification of the exercises
Documenting a Function#
When writing a function, it is important to document it, that is, to provide
clear and precise information about what the function does, how to use it
correctly, and what to expect in terms of behavior and results. This
documentation is generally written in the form of comments in the source code of
the function.
Example:
def factorielle(n):
""" Fonction qui calcule la factorielle
Paramètre n : un nombre entier positif
Renvoie n!
"""
Good documentation:
Is concise and precise
Gives the preconditions on the parameters
Describes the result (what the function does)
Tip for being effective:
Always start by writing the documentationIn any case, you have to think about what the function will do!
Function Tests#
In computer science, it is important to learn how to write tests that allow you to
validate the correct functioning of your functions and programs.
In Python, there is a keyword, assert
, which allows you to test a boolean expression.
You have already encountered it in previous practical sessions. If this expression evaluates to True,
nothing happens.
Tips to be effective:
Start by writing the tests for a functionAnyway, you have to think about what it will do!
Test specific cases.
As long as we are not sure that the function is correct:
Make additional tests.
Capitalize these tests in the form of tests.
If we find a bug:
Add a test characterizing the bug.
Tip
Pre-existing functions in Python In Python, you can call many pre-existing functions. You have already seen
some: type()
, print()
, range()
… We will discover others as we
go through the practical exercises.
Exercise 1: return versus display#
The following two cells define the functions
abs
andafficheAbs
respectively; note the differences between these two functions, then execute the cells.
def abs(a):
""" Une fonction qui calcule la valeur absolue
Paramètres : a, un entier
Renvoie : la valeur absolue de a
"""
if (a > 0):
return a
else:
return -a
def afficheAbs(a):
""" Une fonction qui affiche la valeur absolue
Paramètres : a, un entier
"""
if (a > 0):
print(a)
else :
print(-a)
Observe the following calls; is there a difference between
abs
andafficheAbs
?
abs(-3)
3
abs(-3)
3
afficheAbs(-3)
3
afficheAbs(-3)
3
Hint
Explanation
abs
returns a value while afficheAbs
displays it. Note above
that, with abs(3);
, Jupyter does not show the value at all, whereas with abs(3)
Jupyter shows the value with its type (int
). Conversely, afficheAbs
displays the
value but does not return it.
Exercise 1 (continued)
Try to guess the result of the following calls and then execute to verify:
abs(-5) + abs(3)
8
afficheAbs(-5) + afficheAbs(3)
5
3
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[8], line 1
----> 1 afficheAbs(-5) + afficheAbs(3)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'
The second cell gives you an error, do you understand why?
Explanation
afficheAbs
only displays a value without returning it (return type void
); it is
therefore not possible to reuse this value later, for example to perform a calculation or
a test.
Exercise 2: A function that uses a function#
Complete the function below, for which the documentation is provided.
⚠️ **You must use a call to one of the two preceding functions, afficheAbs
or
abs
; which one should you choose? Why?** ⚠️
def distance(a, b):
""" Distance de deux points sur une droite
Paramètre : a un entier: la coordonnée du premier point
Paramètre : b un entier: la coordonnée du deuxième point
Renvoie : la valeur absolue de la différence entre a et b
"""
### BEGIN SOLUTION
return abs(b-a)
### END SOLUTION
Check the behavior of your distance
function on the example below; try
it on a few other examples; correct the function if necessary:
distance(5,3)
2
The tests below partially automate the verification of your function’s behavior; since
the expected value is specified, all that remains is to verify that you indeed obtain
true
each time:
distance(5,3) == 2
True
distance(-4,2) == 6
True
distance(2,-5) == 7
True
Exercise 3: Automatic tests#
In the previous exercise, we tested the distance
function. However, it was necessary to
execute the three test cells separately and ensure for each of them
that true
was displayed and not false
. To only be notified if there is a problem and
know where it comes from, we will gather the tests into a single cell using
the test automation infrastructure seen in the previous tutorials.
Try the following examples. .
Tip
Each time you restart the kernel, then go to Cellule
->
Exécuter toutes les précédentes
. This executes all the cells that are before the one
where you are. This will save you time looking for the
cells that need to be re-executed.
assert ( 1 < 2 )
assert ( 1 > 2 )
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Cell In[14], line 2
1 assert ( 1 < 2 )
----> 2 assert ( 1 > 2 )
AssertionError:
We note that if the condition in the parameter of assert
is true, there is no display.
On the other hand, if the condition is false, an error message indicating the false
condition is displayed.
With assert
, the tests for the distance
function take the following form:
assert ( distance(5,3) == 2 )
assert ( distance(-4,2) == 6 )
assert ( distance(2,-5) == 7 )
### BEGIN HIDDEN TESTS
assert ( distance(-5,-2) == 3)
### END HIDDEN TESTS
Run these tests. Running them should not display anything.
Execute the following two cells to define and test the maxAbs
function.
Correct the function so that it passes the tests.
def maxAbs(a, b):
""" Une fonction qui renvoie la valeur absolue du plus grand des deux entiers
en valeur absolue
Paramètre : a, un entier
Paramètre : b un entier
Renvoie : la valeur absolue du plus grand des deux entiers en valeur absolue
"""
print(abs(a))
print(abs(b))
if abs(a) >= abs(b):
return a
else :
return b
assert( maxAbs( 6, 2) == 6 )
assert( maxAbs(-15, 5) == 15 )
assert( maxAbs( -2, -3) == 3 )
6
2
15
5
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Cell In[17], line 2
1 assert( maxAbs( 6, 2) == 6 )
----> 2 assert( maxAbs(-15, 5) == 15 )
3 assert( maxAbs( -2, -3) == 3 )
AssertionError:
Exercise 4#
Same instructions as for exercise 1:
def sommeAbs(a, b):
""" somme des valeurs absolues (aussi appelée norme L1)
Paramètre : a un entier
Paramètre : b un entier
Renvoie : la somme des valeurs absolues de a et b
"""
### BEGIN SOLUTION
return abs(a) + abs(b)
### END SOLUTION
sommeAbs(5,-3)
8
sommeAbs(5,-3) == 8
True
sommeAbs(-4,-2) == 6
True
sommeAbs(2,5) == 7
True
Exercise 5: Follow the documentation and tests#
Implement the function nombreSecondes
whose documentation is given below:
### BEGIN SOLUTION
def nombreSecondes(j, h, m, s):
""" Renvoie en secondes la durée décrite en jours, heures, minutes, secondes
Paramètre : j un entier représentant le nombre de jours
Paramètre : h un entier représentant le nombre d heures
Paramètre : m un entier représentant le nombre de minutes
Paramètre : s un entier représentant le nombre de secondes
Renvoie : la durée totale en secondes
"""
return s + (60 * (m + 60 * (h + 24*j)))
### END SOLUTION
Check its operation on the examples and tests below:
nombreSecondes(1,1,1,1)
90061
assert( nombreSecondes(0,0,0,1) == 1 )
assert( nombreSecondes(0,0,1,0) == 60 )
assert( nombreSecondes(0,1,0,0) == 3600 )
assert( nombreSecondes(1,0,0,0) == 86400 )
assert( nombreSecondes(3,2,5,25) == 266725 )