Introduction to functions#
introductory paragraph
make the link with the Laby exercises; especially when we talk about modularity
more practice exercises; including with Laby?
the spiel on modularity is possibly redundant with the course on functions
Motivation#
Let’s return to our example of the sheet
Variables : “*Calculate the kinetic energy
\(\frac12 m v^2\) of an object with a mass of \(14,5\) kg depending on whether it goes to \(1\), \(10\), \(100\), or
\(1000\) km/h*”.
Here’s how we proceeded:
v = 100
m = 14.5
1. / 2 * m * v * v
72500.0
Using this approach, to understand this code, the reader must recognize the
formula to deduce theintention: calculate the kinetic energy. Furthermore, each
time we need to calculate kinetic energy, we will have to rewrite this formula.
To avoid this, we should distinguishthe intention (calculating kinetic
energy) fromhow to achieve it (using the formula \(\frac12 mv^2\)). For this
we candefine afunction, called energie_cinétique
which describes how
to calculate, from a mass m
and a velocity v
, the kinetic energy of an object of
mass m
and velocity v
:
def énergie_cinétique(m, v):
return 1. / 2 * m * v * v
That being done, each time we want to calculate a kinetic energy, we
can call the function by specifying the value of the mass and the speed, without
having to worry about how a kinetic energy is calculated:
énergie_cinétique(14.5, 100)
72500.0
énergie_cinétique(14.5, 10)
725.0
Functions#
In computer science, a function is a block of code that performs a specific task and
can be reused multiple times in a program. Functions make
the code more modular, easier to read, and easier to maintain.
Definition: Function
Informally, a fonction (programming function (informal)) is a small program
named with:
Input: parameters
A process
Output: a returned value
In our example:
def énergie_cinétique(m, v):
return 1. / 2 * m * v * v
the name of the function, introduced by the keyword def
is énergie_cinétique
. The
input
consists of two parameters m
and v
(real numbers). The process is the calculation
of the expression 1. / 2 * m * v * v
. The returned value, indicated by the keyword
return
is the value of this expression.
Hint
Functions and modularity Functions help to modularize the code, that is, to structure them into small
reusable and composable elements for:
more ease: solve a small problem at a time (analytical method).
more conciseness: avoid repetitions.
more readability: separation of intention (the what) and the how (encapsulation).
Hint
Indentation in Python In our function example, the processing to be performed consists of a single
instruction:
return 1. / 2 * m * v * v
More generally, the processing could consist of a block of several instructions.
In Python, the syntax for delimiting such a block of instructions uses
indentation (indentation): each line of the instruction block is preceded by four
spaces. In addition, the instruction block is introduced by the character :
at the end
of
the line preceding the block. Other languages use curly braces {
and }
, parentheses
(
and )
, or keywords like begin
and end
.
This particularity of Python promotes readability.
Exercise
Define a function
aire
that takes the radiusr
of a disk as a parameter and calculates its area:
pi = 3.1415
### BEGIN SOLUTION
def aire(r):
return pi * r * r
### END SOLUTION
Exercise (continued)
Call this function to calculate the area of a disk with radius \(3\)
### BEGIN SOLUTION
aire(3)
### END SOLUTION
28.2735
The following cell allows you to test your function; if nothing is displayed, there is a good chance that your function is correct:
assert aire(0) == 0
assert aire(1) == pi
assert round(aire(3), 4) == 28.2735
Exercise (continued)
Same thing for the perimeter of the disk:
### BEGIN SOLUTION
def périmètre(r):
return 2 * pi * r
### END SOLUTION
### BEGIN SOLUTION
périmètre(3)
### END SOLUTION
18.849
assert périmètre(0) == 0
assert périmètre(1/2) == pi
assert périmètre(3) == 18.849
Conclusion#
In this sheet, you have defined your first
functions, which take parameters as input,
perform a process, and then return a value. Then you called
them to perform calculations, without having to worry about how these
calculations were performed. This is a first tool to facilitate the
modularity of the programs.
We will explore functions further later and explore other tools to
promote modularity.
Before moving on, we offer some self-correcting training and
revision exercises on functions. Run the following cell, follow the
instructions that appear, and click Valider
to check your answer. Use
the different buttons to browse the exercises and their possible variations.
Attention
The tool used, Jupylate, is under development; it has some flaws such as
the lack of automatic indentation or syntactic coloring in the
response area.
the additional indications below: You can add indentations by making 4 spaces, or code your function in a new cell and then copy / paste it into the response area.
^^^html_block```{todo} Re-enable the execution of the next cell.
<!-- ```{code-cell} ipython3 -->
^^^html_block```python
---
nbgrader:
grade: false
grade_id: cell-545519ced0ffb1df
locked: true
schema_version: 3
solution: false
task: false
---
import glob
from jupylates import Exerciser
exercises = glob.glob('../exercices/fonctions/*.md')
Exerciser(exercises, lrs_url="../.lrs.json", mode="train")