Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
44 views

Intro Programmation en Python Pour Les Mathématiciens-English

Uploaded by

Verla Mfeer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Intro Programmation en Python Pour Les Mathématiciens-English

Uploaded by

Verla Mfeer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

AlexandreCasamayou-Boucau

PascalChauvin
GuillaumeConnan
Lessons and exercises
Programming
in Python for
mathematics
2
nd
edition
© Dunod, 2012, 2016
5 rue Laromiguière, 75005 Paris
www.dunod.com
ISBN 978-2-10-073831-1
Preface to the first edition
In this work devoted to the study of the Python language, Alexandre Casamayou-Boucau,
Guillaume Connan and Pascal Chauvin have achieved a dif fi cult synthesis: that of presenting a
clear introduction to the language itself, while explaining its deep links with
algorithmic mathematical.
It is certain that the choice of Python made this synthesis a priori possible: thanks to
its multi-paradigm programming syntax, writing programs in Python is
both powerful and affordable; it is likely to cover most areas of
programming, and especially those that may be of interest to algorithms.
From this point of view, learning a “fundamental” language like Python
seems to us to be a much better didactic alternative to that which would consist in learning
only the use of computer algebra software: to give an analogy, let's say that c is
a bit of the difference between mastering the operation and the mechanics in depth.
fucking an automobile, and just knowing how to drive it! The fact that Python is
entirely open source and widely used in the industry also guarantees its accessibility,
durability and scalability over time; this is not necessarily the case with
proprietary software which, for this reason, cannot be recommended in the same way for
educational programs.
The work should lead the reader to deepen his knowledge of the
principles of programming and his understanding of fundamental mathematical algorithms
. It is built from numerous and very rich examples which make it
attractive to read . These should also greatly facilitate the task of teachers who will use it
, from high school to preparatory classes and university.
Saint-Martin d'Hères, October 5, 2011,
Jean-Pierre Demailly
Professor at the University of Grenoble I
Member of the Académie des Sciences

Table of contents
Foreword vii
1 Introduction to the Python language 1
1 Why Python? ....................................... 1
2 Before starting ... ... ................................. 2
3 Using Python as a calculator .......... .................. 2
4 Variables and assignments ........................... ......... 3
5 Functions ...................................... ...... 6
6 Writing and reading instructions ............................. 10
7 The conditional structure. ................................. 14
8 While loops ............ ........................... 18
9 Lists ................... .......................... 20
10 The for loops ................... ...................... 28
11 Summary of the main types ..................... ....... 31
12 A few words on recursion ............................... 33
13 Some methods for sorting a list ........................... 35
14 Some usual primitives ............... ................... 37
15 A word about exceptions ........................ ........... 40
16 Complements on functions ................................ 41
17 Notions on classes ......... ............................ 43
18 Training exercises ................ ................... 49
2 Modules 51
1 Structure of a module ..................... ................ 51
2 Some “Batteries included” modules .......................... 53
3 Reading and writing to a fi le ................................. 64
4 Handling CSV fi les ... .............................. 68
5 How to generate graphics? ............. ................. 70
6 A glance at the Matplotlib module ...................... .... 74
7 Training exercises ................................... 75
3 Mathematical topics 77
1 Matrices ............................................. 78
2 The numbers: between analysis and algebra ........................... 112
3 The number π ............ ............................... 149
4 Probabilities ................ ........................... 163
5 Binary relations and graphs ..... ............................ 170
4 Numerical methods 179
1 Numbers in scientific notation ........... .................. 180
2 Solving nonlinear equations ........................ ..... 182
3 Numerical solution of di ff erential equations ...................... 186
4 Polynomial interpolation ........... ........................ 199
5 Numeric branch ...................... ............... 203
vi Programming in Python for mathematics
6 Numerical integration ........................ ............. 205
7 Training exercises ............................... .... 216
5 Recursion 217
1 Some examples ....................................... 217
2 Spiral of pentagons ..................................... 225
3 Dragon curve ... .................................... 226
4 Sierpińsky Triangle ......... ........................... 228
5 Sums of terms of a geometric sequence ............. ........... 232
6 Training exercises ............................ ....... 233
6 Classes 236
1 Graphs ..................................... ........ 238
2 Representation of numbers .................................. 243
3 Lists ............................................... 257
4 Binary trees ......................................... 266
5 Calculator ... ........................................ 275
6 Polynomials and rational fractions .... .......................... 291
7 Training exercises .................. ................. 300
Bibliography 302
General index 305
Index of commands 309
Foreword
The production of a computer program in the traditional way necessarily involves
writing its source code. It is this aspect of programming that
particularly interests us. A true writing activity in itself, so frequent in
learning, it is precisely through this phase - which can be laborious but also so
rewarding - that the desired result is obtained. It seems important to us to convince the
students of this.
All the work is to analyze a problem and describe a way to get a
solution. Deprived of any capacity for deduction or anticipation, the “robot”, itself - interpreter
or compiler - is content to execute strictly only what the author of the program
has explained. The greatest rigor is therefore required. This requirement required in
programming, the practice of which is still quite new for college and high school students,
can only be of benefit to them in the long term in other learning.
Of course, modern software development environments (“Rapid Application
Development” in English terminology) abound in
programmer assistance devices , in the tools used. But above all, in recent years, there has been
modular programming and object design, which have made it possible to segment gigantic
projects for a common realization, shared by hundreds of individuals. The fact
remains that the phases of writing continue, what is more with programming languages
which are at the start of the third millennium more than two thousand, while this
activity has really taken off. shortly before World War II.
If the programming makes use of the algorithm to be efficient, it must also be
able to provide in addition programs which are at the same time readable, easy to use and
modifiable by other users. Since FORTRAN (1956), a language which left the user very
close to the machine, languages have not ceased to evolve towards a more "high level", namely,
becoming more and more accessible.
For example, here are three routines (the first function is expressed in C language, the second
in CaML language, the third in Python language) calculating the factorial of a
natural integer n:
factorial.c
long factorial (long n) {
long result = 1;
unsigned long i;
if (n <0)
return -1;
for (i = 1; i <n + 1; ++ i)
result
*
= i;
return result;
}
factorial.ml
let rec factorial = function
| 0-> 1
| n-> n
*
factorial (n-1) ;;
factorial.py
def factorial (n):
ifn> 0: return n
*
factorial (n-1)
else: return 1
viii Programming in Python for mathematics
Apart from the fact that the C version is written in an iterative style where the language CaML is
formidably efficient with regard to recursion, what is the highest
level language? ...
In mathematics, high level languages based on a logical formalism are of great
interest to us because they have this rigor that befits our discipline and are at the
same time less parasitized by the technological details of languages too close to the machine
or too loose logically speaking.
However, languages such as C are widely used (because they are linked to
UNIX systems), as is object programming, so popular for the realization of
man / machine interfaces of industrial programs.
This is why we have chosen the Python language. It has proven itself as an
object-oriented language , while also allowing for imperative and recursive programming.
Python has a clear syntax and remains particularly affordable for beginners,
while offering high-level constructs.
The languages cited here are, among others no less important, widely used and
developed by teams at the forefront of computer research. They have been designed and improved
for years and avoid the pitfalls of certain interfaces that are supposedly simple to
handle but which can hide many flaws and will not lead to any use
outside of high school.
As we continue to do mathematics and calculate with paper and pencil,
so we prefer a programming context as sober as possible, stripped of all
that is useless and that hinders thinking. A simple text editor (not word
processing software ) does the job well, along with a console (
*
N
*
X preferably)
for interpreting or compiling, then running a program. . It's really
about focusing on the essentials, and we see students accepting this work, to the extent
that the payoff is immediate: either the program works, or it doesn't,
or it does something other than that. than its author predicted. No other reward
is aimed at other than the intellectual satisfaction inherent in learning. This is a priority for
the school.
How to use this book?
This book has two objectives: to introduce programming in Python and to
apply the concepts thus acquired to mathematics.
After a first
chapter presenting the fundamentals of the Python language, a second chapter deals with the
notion of module. On the one hand, it is explained how to program a
personal module; on the other hand, we present some of the very many modules provided
by default with Python
1
. Regarding the most
well-known third-party modules to scientists (NumPy and SciPy for numerical computation,
Matplotlib for
graphs, SymPy for algebra), we will only briefly mention them here or
1. We will not discuss the modules allowing the manipulation of SQL databases. with Python. The
reader
interested in this subject can, for example, consult chapter 16 of the work [Swi10], an electronic
version of which
is freely downloadable from the site of its author.
Foreword ix
there: indeed, their detailed presentation goes well beyond the scope of this work. In addition,
for the plotting of functions, we have chosen to develop, for educational purposes, a
small module allowing to generate a graphic in PostScript format from a list of
points to be plotted.
The following chapter proposes to present a varied list of mathematical algorithms
programmed as simply as possible in Python: several arithmetic
algorithms are illustrated (EUCLID's algorithm, primary tests, etc.), decryptography (
HILL encryption , deVIGENÈRE, RSA system, etc.), the problems of
decimal approximation (calculation of the first decimal places ofπ by the methods of Nicolas DE
CUES, John
MACHIN, deBRENT and SALAMIN, etc.), problems of probabilities and of graph theory.
Then, the classical methods of numerical analysis are reviewed: solving
various equations, ordinary differential equations, numerical derivation and integration
.
The last two chapters are more focused on algorithms. After having
dealt with the notion of recursion, the last chapter takes as a guiding
thread several implementations of a small formal computer: some
classical data structures (trees, graphs, stacks, queues, etc.) and the oriented design are
approached. object,
one objective of which is to obtain, by means of abstraction, a good modularity, so useful for
large projects.
Some programs a little too long to figure on the paper version are
available in an archive, which also contains all of those in the book, and which can be
downloaded from the www.dunod.com page dedicated to this work.
The concepts exposed in this book are illustrated by exercises distributed throughout
each chapter. In addition, at the end of the chapter, training exercises are grouped together
, the answers to which are available on the dunod.com site from the home page of the
work.
The book is aimed in particular at high school mathematics teachers. They will be able to
verify that the use of the Python language is a very good choice for teaching
algorithms in new mathematics programs. High school
students and undergraduates and preparatory classes can also find something to
stimulate their programming learning here.
No computer knowledge is required to read this book.
Conventions for the presentation of the code
To write the code, you will encounter several presentations:
- the instructions preceded by chevrons in a gray box must be entered in an
interactive session ;
>>> 1 + 1
2
x Programming in Python for mathematics
- instructions without angle brackets in a gray box are pieces of code to be written
in a fi le;
print ('Hello!')
- the instructions in a gray box with a dark line to the left and an
italicized fi le name above the box are excerpts from a fi le in the
downloadable archive on the site from the publisher; in this case, if the result of the execution of
the script
is presented, it appears immediately after the script on a white background;
fi le.py
#! / usr / bin / python3
#-
*
- coding: Utf-8 -
*
-
print ('Here is the result.')
Here is the result.
- two horizontal lines delimit a session in a Unix terminal:
Terminal
$ python3 file.py
Here is the result.
$ python3
Python 3.1.3 (r313: 86834, Nov 28 2010, 11:28:10)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 + 1
2
Acknowledgments
We would like to warmly thank all those who reread the manuscript of this book:
Alain BUSSER, Stéphane GROGNET, Hubert H. HUPKES, Gérard KUNTZ, François PANTIGNY and
Aymar DE SAINT-SEINE.
We also thank our students and pupils for serving as “guinea pigs” and
suggesting improvements to our programs.
Finally, we warmly thank Jean-Pierre DEMAILLY who agreed to preface this
work.
1
Introduction to the Python language
Contents
1 Why Python? .............................. 1
2 Before starting ..... ......................... 2
3 Using Python as a calculator .................. 2
4 Variables and assignments .......................... 3
5 Functions ................ ................... 6
6 Reading and writing instructions ................... 10
7 The conditional structure ......................... 14
8 While loops .................. ............ 18
9 Lists .................................. . 20
10 The for loops ............................... 28
11 Summary of the main types ...... ............ 31
12 A few words on recursion ..................... 33
13 Some methods for sorting a list .. ............... 35
14 Some usual primitives ........................ 37
14.1 Some primitives of common use ............... 38
14.2 Type conversion primitives ................... 38
14.3 Iterators ... ................ .............. 39
15 A word on exceptions ......................... 40
16 Additional information on functions ...................... 41
17 Notions on classes .................... ....... 43
18 Training exercises .......................... 49
1 Why Python?
The Python programming language is a great choice for both
programming initiation and programming itself. It is a very high level language
whose syntax encourages writing clear and quality code. In the area of
memory management , many low-level details specific to languages like C disappear.
In addition, learning Python is facilitated by the existence of an interactive interface. However
, its interest is not reduced to learning programming or algorithms;
2 Programming in Python for mathematics is
growing in popularity. The summer has been chosen by major players: Google, YouTube,
NASA, etc.
Technically speaking, Python is a language where you can choose from several programming
styles
. It promotes structured imperative programming and
object-oriented programming ; to a lesser extent, it allows programming in a functional style
1.
It
has strong dynamic typing, automatic memory management by garbage
collection and an exception management system. It is a multi-platform, versatile
(even in fields such as the web, graphics, network), “open source”, and
free.
Finally, the use of Python can be combined with that of the free computer software
Sagemath
2
since the latter is written in Python.
If this brief plea didn't convince you, give Python a try, you will definitely
adopt it.
2 Before you begin ...
To install Python, all you need to do is download version 3 which corresponds to your operating
system
(Windows or Mac) at the address: http: //www.Python.org/
For this which is Linux systems, Python is usually already installed by default, and Idle can
be found in the repositories of most distributions. For BSD systems, if Python
is not already installed as a dependency, use packages or ports.
As a supplement to this chapter of Python Language Basics, the reader will
also be able to benefit from the first five sections of the of fi cial Python tutorial:
http://docs.python.org/py3k/tutorial/
3 Using Python as a calculator
If you have never programmed, the easiest way to to execute Python statements is
to use the specialized environment Idle. This environment consists of a window called either
console, shell or Python terminal.
The command prompt is made up of three chevrons; all you have to do is enter an instruction
and then press the "Enter" key on your keyboard.
We will not deviate from the computer tradition which consists in starting the learning
of a language by the display
3
of a greeting:
>>> print ("Hello!")
Hello!
The Python console works like a simple calculator: you can type an expression into it
, the value of which is returned as soon as you press the “Enter” key.
1. This aspect will not be addressed in this work; the interested reader can refer to the “Functional
Programming HOWTO” page of the documentation: http:
//docs.python.org/py3k/howto/functional.html.
2.See http://www.sagemath.org/ethttp: //www.sagemath.org/fr/.
For an introduction to Sagemath, you can consult the electronic book Calcul mathematics with
Sage
freely downloadable at the address http://sagebook.gforge.inria.fr/.
3. Python 2 users will notice that starting with version 3, the print statement is replaced by the
print () function. For more details, see http://docs.python.org/3.1/whatsnew/3.0.html.
Introduction to Python 3
>>> 2
*
5 + 6- (100 + 3)
-87
>>> 7/2; 7/3
3.5
2.3333333333333335
>>> 34 // 5; 34% 5 # quotient and remainder of the Euclidean division of 34 by 5
6
4
>>> 2
**
7 # for the exponentiation (not 2 ^ 7!)
128
By the way, we used the "hash" symbol # to place comments in the
lines of ordered; anything to the right of a # symbol (up to a new
line) is simply ignored by the interpreter.
To browse the history of instructions entered in the Python console, you can
use the shortcuts Alt + p (p for previous) and Alt + n (n for next).
4 Variables and Assignments
What exactly happens when you type a number (eg 128) into the Python console
? Well, let's say, as a first approximation, that the interpreter creates a new "object"
(without specifying the meaning of this word for the moment) and keeps it in memory.
>>> 128, id (128), type (128)
(1, 137182768,)
This object has a value (here 128), an
identifier, that is to say an “
identity card ” allowing to know where it is kept
in memory (here 137182768), and finally a
type
4
( here the integer type called int).
128
137182768
int
The least we can say is that the identifier hardly speaks to us ... Hence the interest of
assignments. Instead of designating 128 by its identifier, we will give it a name that is easy
to handle. Instead of calling the object “Mr. 137180768”, we will call it “Mr. A.”,
after having indicated to the interpreter once and for all the identification made by a message
of the type: “Mr. A. alias Mr. 137180768 ”.
In practice, an assignment is made using the symbol "=", like this:
>>> a = 128
>>> a
128
>>> a, id (a), type (a)
(128, 137180768 ,)
>>> 2
*
a
256
a
128
137182768
int
4. The notion of type will be detailed in section 11 page 31.
4 Programming in Python for mathematics
So each time we call the number 128, we just have to invoke the variablea.
Note that the object designated para is always object 128, still stored at the same address.
Be aware that the assignment statement “=” does not have the same meaning
as the equality symbol “=” in mathematics
5
. For example, the first is not
symmetrical, while the second is: wanting to exchange the order of the elements in an
assignment statement will inevitably produce an error in the interpreter:
>>> 128 = a
File "", line 1
SyntaxError: can't assign to literal Now
let's do the following assignment sequence:
>>> b = a
*
2
>>> b # dir .: 256
>>> b, id (b), type (b) # dir .: (256, 137184816,)
>>> a = 0
>>> a, id (a), type (a) # dir .: (0, 137180720,)
>>> b # rep .: 256
Here is a little dif fi culty for those who are new to programming. Contrary to what
our algebraic calculation habits might lead us to believe, the statement b = a
*
2
does not affect b twice the value a regardless of the value of a throughout the
Python session . On the contrary, the instruction b = a
*
2 proceeds in two stages:
- the expression located to the right of the sign “=” is evaluated, that is to say calculated according
to
the state of the memory at this moment : here the interpreter evaluates the double of the value dea;
the
result is an object of integer type, of value 256, and placed in memory with the identifier
137180720.
- then, and only then, the interpreter assigns to the name located to the left of the
assignment instruction (ie b) the object obtained after evaluating the expression on the right.
We notice that the identifier of the object to which the variable b refers no longer has anything to
do with a.
In other words, the object named b no longer has any relation to the object named a. Thus, a
subsequent reassignment of the variablea will not result in any change for the variableb.
Did you understand correctly? So practice by reading the following series of instructions and
noting on a piece of paper the content of each of the variables at each step; then execute
each of these series of instructions in the console and verify that what you wrote down
agrees with what the interpreter displays.
>>> a = 100
>>> b = 17
>>> c = ab
>>> a = 2
>>> c = b + a
>>> a, b, c
>>> a = 3
>>> b = 4
>>> c = a
>>> a = b
>>> b = c
>>> a, b, c
5. This explains that in algorithm books, the affection deexpr àx is often noted x ← expr .
Introduction to the Python language 5
Let's go a little further; It is common in programming that we use a variable
as a counter and therefore need to increment (i.e. increase)
or decrement (i.e. - say decrease) the value of the variable by a certain amount. We
then proceed as follows.
>>> x = 0
>>> x = x + 1
>>> x, id (x), type (x) # dir .: (1, 137180736,)
>>> x = x + 1
>>> x, id (x), type (x) # dir .: (2, 137180752,)
>>> x = x + 1
>>> x, id (x), type (x) # dir .: (3, 137180768,)
Once again, note the difference with algebraic calculus: while the equation x =
x + 1 has no solution, the instruction x = x + 1 is perfectly legal, and even
commonly used in programming.
Let's detail the first instruction x = x + 1 above; this instruction proceeds in two
stages:
- the interpreter evaluates the value dex + 1 at the given instant; the result is an object of type
integer, of value 1, and placed in memory with the identifier 137180736.
- then, and only then, the interpreter assigns to the name which is to the left of
the assignment instruction (namely x) the object obtained after evaluation of the expression on the
right.
Let us point out a shortcut specific to Python which is very useful in practice and which has the
advantage of avoiding
confusion with the manipulation of equations in algebra.
>>> x + = 1 # replace x with x + 1
>>> x - = 3 # replace x with x-3
>>> x
*
= 3 # replace x with x
*
3
>>> x / = 2 # replace x by x / 2
Another interesting shortcut, you can assign the same object to several variables simultaneously
. These two variables then refer to the same object (we sometimes say that they are two aliases
of the same object).
>>> x = y = 3
>>> x, y
(3, 3)
>>> id (x), id (y)
(137180768, 137180768)
x
y
3
137180768
int
You can also make assignments parallel to l 'using a single operator "=". All
expressions are then evaluated before the first assignment.
>>> x, y = 128,256
Once again, it should be understood that an assignment takes place in two stages:
evaluation of the expression on the right then creation of the alias with the name of the term on the
left.
Could you predict the outcome of the following two sets of instructions?
6 Programming in Python for mathematics
>>> x = 19
>>> x = x + 2; y = x
*
2
>>> x, y
>>> x = 19
>>> x, y = x + 2, x
*
2
>>> x, y
Now here is an exercise that should be fully understood before continuing
further.
A fundamental exercise: the exchange of the contents of two variables
We suppose that the variables x ety have as their respective values integers α and β. We want to
exchange the content of these two variables.
a) First method: Propose a method which uses an auxiliary variable tmp.
b) Second method: We execute the following sequence of instructions:
>>> x = x + y; y = xy; x = xy
What are the contents of the variables x ety at the end of the sequence?
c) Third method (the most “pythonic”): Use a parallel assignment.
Solution.
a) >>> tmp = x
>>> x = y
>>> y = tmp
b) We have swapped the values dex ety.
c) >>> x, y = y, x
Let us quickly point out that to delete a variable, we have the functiondel.
Before closing this section, let us specify that the names of variables can be not only
letters, but also words; they can contain numbers (provided you
do not start with a number), as well as certain special characters such as the underscore
"
_
" (called underscore in English). The good programmer of course strives to choose
the most relevant variable names possible.
5 Functions
Suppose we want to compute the images of some numbers by a given
polynomial function. If the function in question is a little long to enter, for example, f: x? →
x
7
−6x
6
+ 15x
4
+ 23x
3
+ x − 9, it is quickly tedious to enter it each time you
want to calculate the image of a number by this function.
A first idea is to use the console history to avoid entering the
function each time :
>>> x = 2
>>> x
**
7-6
*
x
**
6 + 15
*
x
**
4 +23
*
x
**
3 + x-9
161
>>> x = 3
>>> x
**
7-6
*
x
**
6 + 15
*
x
**
4 + 23
*
x
**
3 + x-9
Introduction to Python 7
-357
>>> x = 4
>>> x
**
7-6
*
x
**
6 + 15
*
x
**
4 + 23
*
x
**
3 + x-9
-2885
Nevertheless, we I suspect that there is a way to save this tinkering ...
It is quite possible to de fi ne a function (in the sense of the Python language) which looks like
a mathematical function. The syntax is then the following:
>>> def f (x):
... return x
**
7-6
*
x
**
6 + 15
*
x
**
4 + 23
*
x
**
3 + x-9
. ..
>>> f (2), f (3), f (4) # rep .: (161, -357, -2885)
Let's take a close look at this definition. First, the declaration of a new function
begins with the keyword def. Then, still on the same line, comes the name of the function
(icif) followed by the formal parameter
6
of the function, placed in parentheses (the formal parameter
x of the Python function corresponds here to the dummy variable of the mathematical function),
the
dotted right colon.
Once the first line is entered, we press the "Enter" key and we see that the
chevrons of the command prompt have been replaced by dots. This means that the
interpreter must wait for the rest of the instructions. We must then enter four spaces
to “indent” them. Finally, an empty line will tell the interpreter that our
function definition is complete, and that it can now read the entire block of instructions.
To better understand the rules of de fi nition of functions, let’s briefly give
three errors that should not be reproduced:
>>> # ---> Error 1: forgetting the colon at the end of the line
>>> def f ( x)
File "", line 1
def f (x)
^
SyntaxError: invalid syntax
>>> # ---> Error 2: not respecting the indentation
>>> def f (x):
... return x
**
7 -6
*
x
**
6 + 15
*
x
**
4 + 23
*
x
**
3 + x-9
File "", line 2
return x
**
7-6
*
x
**
6 + 15
*
x
**
4 + 23
*
x
**
3 + x-9
^
IndentationError: expected an indented block
>>> # ---> Error 3: forgetting the word return
>>> def f (x):
... x
**
7-6
*
x
**
6 + 15
*
x
**
4 + 23
*
x
**
3 + x-9
. ..
>>> f (2), f (3), f (4)
(None, None, None)
6. Parameters in parentheses in the header of a function are called formal parameters, as
opposed to the parameters supplied when calling the function called actual parameters.
8 programming in Python for mathematics
What has happened in the last attempt of definition of the function f? Quite simply,
during the execution of the function f, the expression x
**
7-6
*
x
**
6 + 15
*
x
**
4 + 23
*
x
**
3 + x-9
is calculated, but the interpreter, not having received the instruction to return the result, keeps it
to itself: it remains silent and simply returns the objectNone as a value.
Some might be tempted to replace the return instruction with the print function that
we saw in very beginning of this chapter.
>>> def f (x):
... print (x
**
7-6
*
x
**
6 + 15
*
x
**
4 + 23
*
x
**
3 + x-9)
...
>>> f (2), f (3), f (4)
19
113
55
(None, None, None)
Here is an example calculation which will allow us to better understand the fundamental difference
between the return statement and the print function. Suppose we want to
calculate the sum of the images of our function
f evaluated in certain values: >>> def f (x):
... return x
**
7-6
*
x
**
6 + 15
*
x
**
4+ 23
*
x
**
3 + x-9
...
>>> f (2) + f (3) + f (4)
187
>>> def f (x):
... print (x
**
7- 6
*
x
**
6 + 15
*
x
**
4 + 23
*
x
**
3 + x-9)
...
>>> f (2) + f (3) + f (4)
19
113
Traceback (most recent call last):
File "", line 1, in
TypeError: unsupported operand type (s) for +: 'NoneType' and 'NoneType'
What happens in the second case? The interpreter displays the value of the expression
x
**
7-6
*
x
**
6 + 15
*
x
**
4 + 23
*
x
**
3 + x-9 on the screen when it encounters the print function ,
but then it doesn't return any reusable object later, other than always that
None object which resists any addition attempt. In fact, the print function is used for its side
effect.
The moral of the story is that it's best to avoid getting into the bad habit of using the
print function inside functions, unless it is explicitly requested. Most
of the functions that we will use in this book will be functions that contain the
return statement in their de fi nition. Of course, the print function is useful and will be used, but
it will mostly be used outside functions, in sequences of instructions grouped together in
fi les called scripts.
A remarkable property of the return statement is that it always interrupts
the execution of the function. As soon as the interpreter reaches the instruction return something,
it returns
the object something and gives up immediately after the function has been executed. There is
therefore no need
to
place instructions after a return: these instructions will never be read by the interpreter
. We sometimes speak of dead code to denote the lines which follow (within the
de fi nition of a function) the return instruction.
>>> def mult
_
7 (x):
... return 7
*
x
... print ("This will never be printed") # it's dead code!
... return 0 # it's still dead code !!!
...
Another notable fact when de fi ning a function: the variables de fi ned inside a
function are not “visible” from outside the function; they correspond to
dumb variables in mathematics. As soon as the function is executed, the interpreter
erases all traces of the internal variables of the function. We express this by saying that
such a variable is local to the function.
In the following example, the variable x is a local variable to the function f: created during
the execution of the function f, it is deleted when the execution is finished.
>>> def f (y):
... x = 1
... return y
...
>>> f (2)
2
>>> x
Traceback (most recent call last):
File "", line 1, in
NameError: name 'x' is not defined
If a variable x already existed before the execution of the function, everything happens as if,
during the execution of def, this variable was momentarily hidden, then returned at the end of
the execution of the function.
>>> x = 0
>>> def f (y):
... x = 1
... return y
...
>>> f (2)
2
>>> x
0
Last point before closing this section: note that a function can include as many
formal parameters as desired (and possibly none):
>>> def my
_
function (x, y):
... return x
*
2
**
y
...
10 Programming in Python for mathematics
6 Writing and reading instructions
As you learn the language, you follow more and more instructions.
If you want to correct an instruction in such a succession, you have to enter
the following instructions again. In addition, it is often desired to record such a
particular sequence of instructions in order to be able to use it later or modify it. Hence the
need to work with fi les in which we place sequences of instructions.
Under theIdle environment, you just have to open a text fi
le by choosing the NewWindow entry in the File menu or by using the shortcutCtrl-N: we write
instructions directly in the fi le; then we save our fi le under a name of the formetoto.py (the
choice of the extensionpy allowing to benefit from the syntax highlighting); finally com-
RunModule mande the Run menu allows you to start the execution of the contents of your
fi le in the Python console.
Those who have already learned to use a text editor (like Vim or Emacs) will prefer to
write their scripts using such an editor and run their script either using a shortcut that
they have defined, either directly in a console.
Let's start with an example. After writing the following fi le, run it:
#! / Usr / bin / python3
#-
*
- coding: Utf-8 -
*
-
x=2
**
8
x
==== No Subprocess ====
>>>
>>>
Disappointment ... nothing is displayed. In fact, the behavior of the interpreter differs slightly
depending on whether you are working in a Python console or in a text fi le.
In fact, when the interpreter reads a text fi le, it performs the instructions one after
the other, but it does not display anything until it is explicitly requested to do so.
Hence, in the previous fi le, the need to add the print function if we want to
display the value of the variable x. Moreover, it is when one writes scripts
in fi les that the use of the print function becomes useful.
#! / usr / bin / python3
#-
*
- coding: Utf-8 -
*
-
x=2
**
8
print (x)
==== No Subprocess ====
>>>
>>>
256
>>>
In the previous fi le, we have placed two lines which, while being optional, are nonetheless
enigmatic for a beginner: the first, called the “shebang” line, specifies
where is the interpreter
7
to use to execute. the fi le. Users of
Linux or MacOS operating systems can then run this script in a Terminal by entering:
./toto.py as well as python3 toto.py
7. In a terminal, type which python3 to find the absolute address of the executable.
Introduction to the Python language 11
Terminal
$ python3 toto.py
256
$ chmod u + x toto.py # necessary to grant the execution right
$ ./toto.py
256
Sometimes, it happens that we want to execute a script, then
immediately switch to interactive mode : just add the -i option:
Terminal
$ python3 -i myfile.py
The second line of the source fi le specifies the encoding, i.e. the format of
character encoding used in your text fi le. Again this line is optional, but it increases
the portability of your programs from one operating system to another. Depending on whether
your operating system defaults to Latin-1 encoding or Utf-8 encoding (the
latter standard being strongly recommended), use
#-
*
- coding: Latin-1 -
*
- or # -
*
- coding: Utf-8 -
*
-
From now on, to save space, we will no longer mention these two lines.
Now that we know how to execute a series of instructions in a fi le, let's go back for a
moment to indentation in the definition of a function. Write the
following two scripts to fi les , and schedule their execution, then verify by running them:
def f ():
print ('Hello')
print ('Hello')
f ()
def f ():
print ( 'Hello')
print ('Hello')
f ()
Let's take a moment to look at the write function print . This function has
many options that allow you to customize the presentation of the data:
x, y = 3, 1000000000
z = 3.1416
print (x, y, z, sep = '')
print (x, y, z, sep = '; ')
print (x, y, z, sep =' \ n ')
print (' x = ', x, sep =' ', end ='; ')
print (' y = ', y, sep =' ' , end = ';')
print ('z =', z, sep = '')
==== No Subprocess ====
>>>
310000000003.1416
3; 100,000,000; 3.1416
3
1000000000
3.1416
x = 3; y = 1,000,000,000; z = 3.1416
Although we haven't talked about strings yet, we have already used them in
our examples, starting with the famous print ("hello"). A string of characters
(that is, - say a typestring object) is a succession of typographic characters
12 Programming in Python for mathematics
of any length, delimited by single "quotes" (apostrophes) or double
"quotes" (double quotes). Triple quotes allow you to include newlines
inside the string.
print ('-> Here you can use "quotes"!')
print ("-> Here you can use " quotes " !")
print ("" "-> Here is a
line break." " ")
print (" -> You can also \ n wrap it like this. ")
-> Here you can use" quotes "!
-> Here we can use 'apostrophes'!
-> Here is a ...
line break.
-> We can also
switch to the line as well.
To lay out a long character string in a
script fi le on several lines , it is not recommended to use a backslash; the following syntax is
preferable
8
:
print ('-> How to cut a line'
'too long in the source file?')
-> How to cut a line too long in the source file?
The format method
of the object string is a very powerful tool allowing you to create character strings by replacing
certain fields (between braces) by values (passed as an
argument of the format function) after converting them. You can specify inside
each brace a conversion code, as well as the display template. Let us give a few
examples.
>>> x = 1037.123456789
>>> '{: g}'. format (x) # choose the most suitable format
'1.04e + 03'
>>> '{: .3f}'. format (x) # fixed the number of decimal places
'1037.123'
>>> '{: .3e}'. format (x) # scientific notation
'1.037e + 03'
>>> '{0: 20.3f}'. format (x) # specifies the string length
'1037.123'
>>> '{0:> 20.3f}'. format (x) # right justified
'1037.123'
>>> '{0: <20.3f}'. format (x) # justified left
'1037.123'
>>> '{0: ^ 20.3f}'. format (x) # centered
'1037.123'
>>> '{0: +. 3f}; {1: +. 3f} '. Format (x, -x) # always displays the sign
' +1037.123; -1037.123 '
>>>' {0: .3f}; {1: .3f} '. Format (x, -x) # displays a space if x> 0
8. For more details, cf. the last section of http://docs.python.org/release/3.1.3/howto/doanddont.
html
Introduction to the Python language 13
'1037.123; -1037.123 '
>>>' {0: -. 3f}; {1: -. 3f} '. Format (x, -x) # is equivalent to' {0: .3f} '
' 1037.123; -1037.123 '
For a detailed description of the format method, we refer to the Py-
thon documentation : http: //docs.python.org/py3k/library/string.html
After the write instruction print which allows a program while executing to display
some results, let's move on to the read input instruction which, in
the opposite direction, asks the user to supply data to the program being
executed.
Or write a small script that asks the user to provide a number, which assigns it to the
variablex, and which returns the square of this number.
x = input ('Enter a value for the x variable:')
print ("{} ^ 2 = {}". format (x, x
**
2))
Enter a value for the x variable: 3
Traceback (most recent call last):
File "test.py", line 5, in
print ("{} ^ 2 = {}". format (x, x
**
2))
TypeError: unsupported operand type (s) for
**
or pow (): 'str' and 'int'
Disappointment, our attempt fails : we notice that the value 3 has nevertheless indeed been
recovered by the program and that the variable x seems to contain the integer 3. However, it is not.
What the variable x contains is the character string "3". And a character string can
not be squared.
Hence the need to talk sooner or later about the type of an object ... Without going into too much
detail about
how a computer works, remember that all information, and in particular the
content of a variable, must be coded in binary. But the “dictionary” for encoding or
decoding the content of a variable will not be the same depending on whether we are dealing with
an
integer, a number in scientific notation or a string of characters. Under these conditions,
knowledge of the binary content of a variable is not sufficient to determine the
corresponding information . It is also necessary to know how the value therein is
encoded. This distinction corresponds to the notion of type.
To know the type of an object, we have already seen that we have the
type function: >>> type (3), type ("3"), type (x)
(, , )
So 3 is of the integer type (int being the abbreviation of the word "integer"), while "3" is of
the character string type (str being the abbreviation of the word "string").
To make our script functional, it is then necessary to call the eval function
which evaluates the expression represented by a character string.
x = eval (input ('Enter a value for the variable x:'))
print ("{} ^ 2 = {}". format (x, x
**
2))
Enter a value for the variable x: 3
3^2=9
14 Programming in Python for mathematics
In a similar vein, let us quote the function exec which makes it possible to carry out an instruction
represented by a character string.
Let’s give a small example without detailing it (to whet our appetite, it brings up the
math module which allows you to import the usual mathematical functions, as well as certain
usual constants such as the numberπ).
from math import
*
x = eval (input ('x =?'))
function = input ('f =?')
code = ("def f (x):"
"return {}". format (function))
exec (code)
print ('{:. 6f}'. format (f (x)))
x =? pi / 4
f =? sin (x)
0.707107
To end this section, where we learned how to write small scripts in files,
let us point out that it is good to get into the habit of presenting your code in Python right away
according to the following conventions:
- size of indentations: 4 spaces;
- maximum line size: 79 characters;
- always place a space after a comma, a semicolon or a colon (except for
the slice syntax);
- never place a space before a comma, a semicolon or a colon;
- always place a space on each side of an operator;
- do not place a space between the name of a function and its list of arguments.
# Deprecated
def f (x):
return 1
x = 1; y = 2; z = 3
x, y, z
f (z)
# Recommended
def f (x):
return 1
x = 1; y = 2; z = 3
x, y, z
f (z)
For more details , we refer to the following link: http://docs.python.org/py3k/
tutorial / controlflow.html # intermezzo-coding-style
7 The conditional structure
Suppose we want to define the absolute value function: | x | =
?
x if x ≥ 0
−x if x <0
We must then use an instruction which operates a disjunction of cases.
In Python, this is the choice statement introduced by the keyword. The syntax is then
the following:
Introduction to the Python language 15
def vabs (x):
ifx> = 0:
return x
else:
return -x
print ('f ({}) = {}'. Format (2, vabs (2 )))
print ('f ({}) = {}'. format (-2, vabs (-2)))
f (2) = 2
f (-2) = 2
Let's observe the syntax of the choice structure. First, the pattern is followed by a
choice condition : what is the object returned by the interpreter when it evaluates this condition?
>>> 2> = 0 # dir .: True
>>> b = 2> = 0
>>> b, id (b), type (b) # dir .: (True, 137009620,)
The condition "2> = 0" is of a type that we have not yet encountered, namely the
boolean type
9
. A Boolean variable can only take two values: True or False
.
The choice condition is checked when the evaluation of this condition returns the Boolean
True, and the interpreter then executes the sequence of instructions found in the first block
of instructions. Otherwise the interpreter jumps to the instruction block located after the
else keyword and delimited by the indentation.
It should be noted the essential role of indentation which makes it possible to delimit each block of
instructions
and the presence of the colon after the condition of the choice and after the key word else.
Let's take a moment to look at Booleans. To obtain a Boolean variable, we
generally use, as in the previous example, one or more comparison operators
. These operators are eight in number:
x == yx is equal to y
x! = Yx is different from
y x> yx is strictly greater than y
xx> = yx is greater than or equal to y
x <= yx is less than or equal to y
x is y id (x) == id (y)
xiny x belongs to y (see the typelist)
? It is important to distinguish the assignment instruction “=” from the comparison symbol “==”.
To express complex conditions (for example x> −2 and x
2
<5), we can combine
Boolean variables using the three Boolean operators (in increasing order of priority
): or (or), and (and), etnot (no).
Note that Python, unlike many languages, also offers some
nice syntax shortcuts like: (x9. The Boolean name comes from the name of the English
mathematician G. BOOLE (1815-1864).
16 Programming in Python for mathematics
>>> x = -1
>>> (x> -2) and (x
**
2 <5) # dir .: True
>>> (x <= -2) or (x
**
2> 5) # dir .: False
>>> not (x> = -2) # dir .: False
>>> - 2Non-Boolean operators take precedence over comparison operators, which take
precedence over logical operators. However, to improve code readability, it is
best to use parentheses when writing complex conditions.
It is sometimes useful to define Boolean functions, that is, functions which always return a
Boolean value, to perform a complex test.
Here
are two versions of a booleanfunction which takes an argument of three numbers and returns the
boolean True if they are ordered in ascending order:
def order (x, y, z):
ifx <= y <= z:
return True
else:
return False
# or even more simply
def order (x, y, z):
returnx <= y <= z
Note that when the conditions and instructions of a conditional structure are
fairly short, we can write them on a single line:
def value
_
absolute (x):
return x ifx> = 0 else -x
In algorithmic, it is quite frequent that one has to chain disjunctions of cases. In
place of using nested choice, we can present this sequence in a succession of
choices, this second version then representing a more pleasant alternative syntax.
Note once again how much Python offers syntax facilities that make it a
relevant language for learning programming.
Let’s illustrate these two possibilities for de fi ning
a function which takes three numbers a, b and c and which displays a sentence indicating the
number of real solutions of the quadratic equation
ax
2
+ bx + c = 0.
def number
_
solutions (a, b, c):
ifa == 0:
print ("The equation is first degree.")
else:
delta = b
**
2-4
*
a
*
c
if delta> 0:
print ("The equation has two real solutions.")
else:
if delta = = 0:
print ("The equation has a real solution.")
Else:
print ("The equation has no real solution.")
Def number
_
solutions (a, b, c):
delta = b
**
2-4
*
a
*
c

You might also like