Introduction to programmation using the Python language

417
Introduction to programmation using the Python language Rémi Marchal Inorganic Theoretical Chemistry group, ISCR, Rennes [email protected] January, 28 th 2019

Transcript of Introduction to programmation using the Python language

Page 1: Introduction to programmation using the Python language

Introduction to programmation using thePython language

Rémi MarchalInorganic Theoretical Chemistry group, ISCR, Rennes

[email protected], 28th 2019

Page 2: Introduction to programmation using the Python language

First hints

Page 3: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Outline

1. Introduction

2. Variables

3. Functions

4. Modules

Page 4: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Outline

1. Introduction

2. Variables

3. Functions

4. Modules

Page 5: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Outline

1. Introduction1.1 History1.2 What is python ?1.3 Why learning and using Python ?1.4 Some basic rules

Page 6: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

A bit of history

1991 : Guido Van Rossum starts to developthe Python programming language.2001 : Creation of the Python SoftwareFoundation, a non-profit organization aimingat foster development of the Pythoncommunity.2009 : Creation of Python3.

Page 7: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Outline

1. Introduction1.1 History1.2 What is python ?1.3 Why learning and using Python ?1.4 Some basic rules

Page 8: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

What is python ?

Quesaco ?

▶ Python is an Object-oriented language. Is allowsyou to create and manipulate easily some objects

▶ It is an interpreted language, so no compilationneeded

Page 9: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

What is python ?

Quesaco ?▶ Python is an Object-oriented language. Is allows

you to create and manipulate easily some objects

▶ It is an interpreted language, so no compilationneeded

Page 10: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

What is python ?

Quesaco ?▶ Python is an Object-oriented language. Is allows

you to create and manipulate easily some objects▶ It is an interpreted language, so no compilation

needed

Page 11: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Outline

1. Introduction1.1 History1.2 What is python ?1.3 Why learning and using Python ?1.4 Some basic rules

Page 12: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Why Python ?

AdvantagesThere is several advantages in using Python

▶ Strong developer community so a lot of librariesready to be used

▶ A large user community so a lot of forum andtutorial available on the web

▶ Several graphical libraries available

Page 13: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Why Python ?

AdvantagesThere is several advantages in using Python

▶ Strong developer community so a lot of librariesready to be used

▶ A large user community so a lot of forum andtutorial available on the web

▶ Several graphical libraries available

Page 14: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Why Python ?

AdvantagesThere is several advantages in using Python

▶ Strong developer community so a lot of librariesready to be used

▶ A large user community so a lot of forum andtutorial available on the web

▶ Several graphical libraries available

Page 15: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Why Python ?

AdvantagesThere is several advantages in using Python

▶ Strong developer community so a lot of librariesready to be used

▶ A large user community so a lot of forum andtutorial available on the web

▶ Several graphical libraries available

Page 16: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

2 ways to write program in python

Through the interpreter

Page 17: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

2 ways to write program in python

Through a script

Page 18: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

2 ways to write program in python

Which way to choose ?

It depends what you want to do.▶ If you just want to do a quite small calculation,

you should use the interpreter▶ If you want to write a quite long program, use the

script▶ If you want to write a program and execute it

several times, use the script

Page 19: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

2 ways to write program in python

Which way to choose ?It depends what you want to do.

▶ If you just want to do a quite small calculation,you should use the interpreter

▶ If you want to write a quite long program, use thescript

▶ If you want to write a program and execute itseveral times, use the script

Page 20: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

2 ways to write program in python

Which way to choose ?It depends what you want to do.

▶ If you just want to do a quite small calculation,you should use the interpreter

▶ If you want to write a quite long program, use thescript

▶ If you want to write a program and execute itseveral times, use the script

Page 21: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

2 ways to write program in python

Which way to choose ?It depends what you want to do.

▶ If you just want to do a quite small calculation,you should use the interpreter

▶ If you want to write a quite long program, use thescript

▶ If you want to write a program and execute itseveral times, use the script

Page 22: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

2 ways to write program in python

Which way to choose ?It depends what you want to do.

▶ If you just want to do a quite small calculation,you should use the interpreter

▶ If you want to write a quite long program, use thescript

▶ If you want to write a program and execute itseveral times, use the script

Page 23: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Outline

1. Introduction1.1 History1.2 What is python ?1.3 Why learning and using Python ?1.4 Some basic rules

Page 24: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Basics rules

What to avoid ?When writing a program in python, there is somebasics rules that you should follow :

▶ Take care about the indentation▶ Avoid infinite loops▶ THINK BEFORE CODING

Page 25: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Outline

1. Introduction

2. Variables

3. Functions

4. Modules

Page 26: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Outline

2. Variables2.1 What is a variable ?2.2 How to define variables and to use it ?2.3 The different types of variables

Page 27: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

What is a variable and why to use it ?

What is a variable ?

▶ A variable is a little place in the Memory of ourprogram and of your computer where you codeshould be able to store data.You can model your computer as a cabinet with alot of drawer, each of them able to store avariable. When you need to access a variable, youjust need to open the proper drawer

▶ Indeed, it is great to be able to make somemathematical operation but if you are not able tostore the result somewhere it is useless.

So no way to write a code without variables

Page 28: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

What is a variable and why to use it ?

What is a variable ?▶ A variable is a little place in the Memory of our

program and of your computer where you codeshould be able to store data.You can model your computer as a cabinet with alot of drawer, each of them able to store avariable. When you need to access a variable, youjust need to open the proper drawer

▶ Indeed, it is great to be able to make somemathematical operation but if you are not able tostore the result somewhere it is useless.

So no way to write a code without variables

Page 29: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

What is a variable and why to use it ?

What is a variable ?▶ A variable is a little place in the Memory of our

program and of your computer where you codeshould be able to store data.You can model your computer as a cabinet with alot of drawer, each of them able to store avariable. When you need to access a variable, youjust need to open the proper drawer

▶ Indeed, it is great to be able to make somemathematical operation but if you are not able tostore the result somewhere it is useless.

So no way to write a code without variables

Page 30: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

What is a variable and why to use it ?

What is a variable ?▶ A variable is a little place in the Memory of our

program and of your computer where you codeshould be able to store data.You can model your computer as a cabinet with alot of drawer, each of them able to store avariable. When you need to access a variable, youjust need to open the proper drawer

▶ Indeed, it is great to be able to make somemathematical operation but if you are not able tostore the result somewhere it is useless.

So no way to write a code without variables

Page 31: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Outline

2. Variables2.1 What is a variable ?2.2 How to define variables and to use it ?2.3 The different types of variables

Page 32: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to create and use variables in Python ?

How to create a variable and address a value ?

In the Python language, it is something extremelysimple to do.Indeed, you just have to write something like this :variable_name=value

ExampleLet assume that you want to create a variable namednb in which you want to store the value 5. Thus, youjust have to write this :nb=5

Page 33: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to create and use variables in Python ?

How to create a variable and address a value ?In the Python language, it is something extremelysimple to do.

Indeed, you just have to write something like this :variable_name=value

ExampleLet assume that you want to create a variable namednb in which you want to store the value 5. Thus, youjust have to write this :nb=5

Page 34: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to create and use variables in Python ?

How to create a variable and address a value ?In the Python language, it is something extremelysimple to do.Indeed, you just have to write something like this :variable_name=value

ExampleLet assume that you want to create a variable namednb in which you want to store the value 5. Thus, youjust have to write this :nb=5

Page 35: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to create and use variables in Python ?

How to create a variable and address a value ?In the Python language, it is something extremelysimple to do.Indeed, you just have to write something like this :variable_name=value

ExampleLet assume that you want to create a variable namednb in which you want to store the value 5. Thus, youjust have to write this :nb=5

Page 36: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Outline

2. Variables2.1 What is a variable ?2.2 How to define variables and to use it ?2.3 The different types of variables

Page 37: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

The different types of variables

Variable typesBasically, there is 3 main type of variables :

▶ The integer (int in Python)▶ The floating ponts (float in Python)▶ The string (str in Python)

Page 38: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Outline

1. Introduction

2. Variables

3. Functions

4. Modules

Page 39: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Outline

3. Functions3.1 What is it ?3.2 Some useful intrinsic Python functions

Page 40: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

What is a function ?A function is a group of instruction that allows you toachieve specific tasks.To call them you just have to use the followingsyntax :name_of_the_function(parameters)It exists several intrinsic functions in Python, some ofthem discussed below.

Page 41: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Outline

3. Functions3.1 What is it ?3.2 Some useful intrinsic Python functions

Page 42: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

The print function

printThis function allows you to display either some text orthe value of a variable on the screen.The syntax of this function is the following :print(what_you_want_to_print)

Example

Python scripta=5.3b=1.2c=a+bprint(a,’+’,b,’=’,c)

Result5.3 + 1.2 = 6.5

Page 43: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

The print function

printThis function allows you to display either some text orthe value of a variable on the screen.The syntax of this function is the following :print(what_you_want_to_print)

Example

Python scripta=5.3b=1.2c=a+bprint(a,’+’,b,’=’,c)

Result5.3 + 1.2 = 6.5

Page 44: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

The print function

printThis function allows you to display either some text orthe value of a variable on the screen.The syntax of this function is the following :print(what_you_want_to_print)

Example

Python scripta=5.3b=1.2c=a+bprint(a,’+’,b,’=’,c)

Result5.3 + 1.2 = 6.5

Page 45: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

The type function

typeThis function returns the type of a variable.Its syntax is :type(nom_of_the_variable)

Example

Python scriptstring=’text’floating=4.5integer=4print(type(string))print(type(floating))print(type(integer))

Result<class ’str’><class ’float’><class ’int’>

Page 46: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

The type function

typeThis function returns the type of a variable.Its syntax is :type(nom_of_the_variable)

Example

Python scriptstring=’text’floating=4.5integer=4print(type(string))print(type(floating))print(type(integer))

Result<class ’str’><class ’float’><class ’int’>

Page 47: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

The type function

typeThis function returns the type of a variable.Its syntax is :type(nom_of_the_variable)

Example

Python scriptstring=’text’floating=4.5integer=4print(type(string))print(type(floating))print(type(integer))

Result<class ’str’><class ’float’><class ’int’>

Page 48: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

variable type conversions

Convert a variable to floating pointThis can be done using the float() Python function.

Example

Python scriptinteger=4string=’5’floating=float(integer)print(floating)floating=float(string)print(floating)

Result4.05.0

Page 49: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

variable type conversions

Convert a variable to floating pointThis can be done using the float() Python function.

Example

Python scriptinteger=4string=’5’floating=float(integer)print(floating)floating=float(string)print(floating)

Result4.05.0

Page 50: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

variable type conversions

Convert a variable to floating pointThis can be done using the float() Python function.

Example

Python scriptinteger=4string=’5’floating=float(integer)print(floating)floating=float(string)print(floating)

Result4.05.0

Page 51: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

variable type conversions

Convert a variable to an integerThis can be done using the int() Python function.

Example

Python scriptfloating=4.9string=’5’integer=int(floating)print(integer)integer=int(string)print(floating)

Result45

Page 52: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

variable type conversions

Convert a variable to an integerThis can be done using the int() Python function.

Example

Python scriptfloating=4.9string=’5’integer=int(floating)print(integer)integer=int(string)print(floating)

Result45

Page 53: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

variable type conversions

Convert a variable to an integerThis can be done using the int() Python function.

Example

Python scriptfloating=4.9string=’5’integer=int(floating)print(integer)integer=int(string)print(floating)

Result45

Page 54: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

variable type conversions

Convert a variable to a stringThis can be done using the str() Python function.

Example

Python scriptfloating=4.9integer=5string=str(floating)print(string)string=str(integer)print(string)

Result4.95

Page 55: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

variable type conversions

Convert a variable to a stringThis can be done using the str() Python function.

Example

Python scriptfloating=4.9integer=5string=str(floating)print(string)string=str(integer)print(string)

Result4.95

Page 56: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

variable type conversions

Convert a variable to a stringThis can be done using the str() Python function.

Example

Python scriptfloating=4.9integer=5string=str(floating)print(string)string=str(integer)print(string)

Result4.95

Page 57: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Store keyboard entries into a variable

keyboard entryThis can be done using the input() Python function.ATTENTION : this keyboard entry will beinterpreted as a string

Example

Python scripta=input(”enter a value”)

a=float(a)print(”a square= ”,a**2)

Resultenter a value 2.5

a square= 6.25

Page 58: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Store keyboard entries into a variable

keyboard entryThis can be done using the input() Python function.ATTENTION : this keyboard entry will beinterpreted as a string

Example

Python scripta=input(”enter a value”)

a=float(a)print(”a square= ”,a**2)

Resultenter a value 2.5

a square= 6.25

Page 59: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Store keyboard entries into a variable

keyboard entryThis can be done using the input() Python function.ATTENTION : this keyboard entry will beinterpreted as a string

Example

Python scripta=input(”enter a value”)

a=float(a)print(”a square= ”,a**2)

Resultenter a value 2.5

a square= 6.25

Page 60: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Store keyboard entries into a variable

keyboard entryThis can be done using the input() Python function.ATTENTION : this keyboard entry will beinterpreted as a string

Example

Python scripta=input(”enter a value”)a=float(a)print(”a square= ”,a**2)

Resultenter a value 2.5

a square= 6.25

Page 61: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Store keyboard entries into a variable

keyboard entryThis can be done using the input() Python function.ATTENTION : this keyboard entry will beinterpreted as a string

Example

Python scripta=input(”enter a value”)a=float(a)print(”a square= ”,a**2)

Resultenter a value 2.5a square= 6.25

Page 62: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Outline

1. Introduction

2. Variables

3. Functions

4. Modules

Page 63: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Outline

4. Modules4.1 What is it ?4.2 Import modules

Page 64: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

What is a module ?

Definition of a moduleA module is basically a piece of code that have beenencapsulated in a file. The variables and functions thatare related to this module are also encapsulated in thefile.Thus, one have just to call the module in order to useits functionalities.

Why to use modules ?There is a lot of different modules that have beendeveloped in Python and it is quite easy to install anduse them.

Page 65: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

Outline

4. Modules4.1 What is it ?4.2 Import modules

Page 66: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to import modules ?

Various methodsIt exists basically 3 ways to import modules1. The basic import method2. Import a module and rename it3. The partial import method

Page 67: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to import modules ?

The basic import methodTo import a module, you can use the following syntaxin your python script :import module_nameUsing this method, all the functions included in themodule are imported. To use one of them, you have touse the following syntax :module_name.function_name

Page 68: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to import modules ?

The basic import method : ExampleLets try to compute the exponential of 0.0. Theexponential function is included in the math module.

Python scripta=0.0res=exp(a)

import mathres=math.exp(a)print(res)

ResultTraceback (most recentcall last) :File ”t.py”, line 2, in<module>res=exp(a)NameError : name ’exp’is not defined

1.0

Page 69: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to import modules ?

The basic import method : ExampleLets try to compute the exponential of 0.0. Theexponential function is included in the math module.

Python scripta=0.0res=exp(a)

import mathres=math.exp(a)print(res)

ResultTraceback (most recentcall last) :File ”t.py”, line 2, in<module>res=exp(a)NameError : name ’exp’is not defined

1.0

Page 70: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to import modules ?

The basic import method : ExampleLets try to compute the exponential of 0.0. Theexponential function is included in the math module.

Python scripta=0.0res=exp(a)

import mathres=math.exp(a)print(res)

ResultTraceback (most recentcall last) :File ”t.py”, line 2, in<module>res=exp(a)NameError : name ’exp’is not defined

1.0

Page 71: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to import modules ?

The basic import method : ExampleLets try to compute the exponential of 0.0. Theexponential function is included in the math module.

Python scripta=0.0res=exp(a)import mathres=math.exp(a)print(res)

ResultTraceback (most recentcall last) :File ”t.py”, line 2, in<module>res=exp(a)NameError : name ’exp’is not defined

1.0

Page 72: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to import modules ?

The basic import method : ExampleLets try to compute the exponential of 0.0. Theexponential function is included in the math module.

Python scripta=0.0res=exp(a)import mathres=math.exp(a)print(res)

ResultTraceback (most recentcall last) :File ”t.py”, line 2, in<module>res=exp(a)NameError : name ’exp’is not defined1.0

Page 73: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to import modules ?

Import a module and rename itThis method is more or less the same as the basicmethod. However, you can change the name of themodule using the following syntaximport module_name as new_name

Page 74: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to import modules ?

Import a module and rename it : ExampleLets try to compute the exponential of 0.0. Theexponential function is included in the math module.

Python scriptimport math as maa=0.0res=ma.exp(a)print(res)

Result1.0

Page 75: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to import modules ?

Import a module and rename it : ExampleLets try to compute the exponential of 0.0. Theexponential function is included in the math module.

Python scriptimport math as maa=0.0res=ma.exp(a)print(res)

Result1.0

Page 76: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to import modules ?

Import a module and rename it : ExampleLets try to compute the exponential of 0.0. Theexponential function is included in the math module.

Python scriptimport math as maa=0.0res=ma.exp(a)print(res)

Result1.0

Page 77: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to import modules ?

The partial import methodInstead of importing the whole module, you canimport only a specific function of it using the followingsyntax :from module_name import function_nameFor example, if you only need the exp function of themath module, you can do :from math import exp

Page 78: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to import modules ?

The partial import method : ExampleLets try to compute the exponential of 0.0. Theexponential function is included in the math module.

Python scriptfrom math import expa=0.0res=exp(a)print(res)

Result1.0

Page 79: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to import modules ?

The partial import method : ExampleLets try to compute the exponential of 0.0. Theexponential function is included in the math module.

Python scriptfrom math import expa=0.0res=exp(a)print(res)

Result1.0

Page 80: Introduction to programmation using the Python language

First hints

IntroductionHistoryWhat is python ?Why learning and using Python ?Some basic rules

VariablesWhat is it ?How ?Variable types

FunctionsWhat is it ?Some functions

ModulesWhat is it ?Import modules

How to import modules ?

The partial import method : ExampleLets try to compute the exponential of 0.0. Theexponential function is included in the math module.

Python scriptfrom math import expa=0.0res=exp(a)print(res)

Result1.0

Page 81: Introduction to programmation using the Python language

Conditional statements and loops

Page 82: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Outline

1. Conditional Statements

2. Loops

Page 83: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Outline

1. Conditional Statements1.1 What is it ?1.2 Indentation1.3 The various conditional statements

Page 84: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

What is conditional statements ?

DefinitionConditional statements is something widely used.Indeed, it allows you to execute a part of the codeonly under specific conditions

Conditional operatorssymbol signification< Strictly inferior> Strictly superior⩽ Inferior or equal⩾ Superior or equal== equal!= different

Page 85: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

What is conditional statements ?

DefinitionConditional statements is something widely used.Indeed, it allows you to execute a part of the codeonly under specific conditions

Conditional operatorssymbol signification< Strictly inferior> Strictly superior⩽ Inferior or equal⩾ Superior or equal== equal!= different

Page 86: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Outline

1. Conditional Statements1.1 What is it ?1.2 Indentation1.3 The various conditional statements

Page 87: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Indentation

What is indentation ?After writing your conditional statement, one shouldintroduce spaces at the beginning of each line in thepart of the code that should be executed if thecondition is fulfill. This amount of space should be thesame for each linesThis is what we call indentation.

Example with algorithma=3b=2If a > b

write a is higher than bwrite b is lower than a

Here, the last 2 lines have been indented (addingspace at the beginning)

Page 88: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Indentation

What is indentation ?After writing your conditional statement, one shouldintroduce spaces at the beginning of each line in thepart of the code that should be executed if thecondition is fulfill. This amount of space should be thesame for each linesThis is what we call indentation.

Example with algorithma=3b=2If a > b

write a is higher than bwrite b is lower than a

Here, the last 2 lines have been indented (addingspace at the beginning)

Page 89: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Outline

1. Conditional Statements1.1 What is it ?1.2 Indentation1.3 The various conditional statements

Page 90: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

The minimal conditional statement (if )

The simple if statementThis allows you to execute some instructions only if acondition if fulfill.The syntax is the following :if condition :

What to do if the condition is fulfill

Python scripta=4.2if a>0 :

print(”a is positive”)

Resulta is positive

Page 91: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

The minimal conditional statement (if )

The simple if statementThis allows you to execute some instructions only if acondition if fulfill.The syntax is the following :if condition :

What to do if the condition is fulfill

Python scripta=4.2if a>0 :

print(”a is positive”)

Resulta is positive

Page 92: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

The minimal conditional statement (if )

The simple if statementThis allows you to execute some instructions only if acondition if fulfill.The syntax is the following :if condition :

What to do if the condition is fulfill

Python scripta=4.2if a>0 :

print(”a is positive”)

Resulta is positive

Page 93: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

The complete conditional (if, elif, else)

The complete conditional statementThis allows you to execute some instructions only if acondition if fulfill and another part if the condition isnot fulfill .The syntax is the following :if condition :

What to do if the condition is fulfillelse :

What to do if the condition is not fulfillIt is also possible to introduce other conditions usingelif.

Page 94: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

The complete conditional (if, elif, else)

Example

Python scripta=4.2if a>0 :

print(”a is positive”)elif a==0 :

print(”a is zero”)else :

print(”a is negative”)

Resulta is positive

Page 95: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

The complete conditional (if, elif, else)

Example

Python scripta=4.2if a>0 :

print(”a is positive”)elif a==0 :

print(”a is zero”)else :

print(”a is negative”)

Resulta is positive

Page 96: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Outline

1. Conditional Statements

2. Loops

Page 97: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Outline

2. Loops2.1 What is it ?2.2 Repeating loop2.3 Conditional loop2.4 Stop a loop

Page 98: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

What is a loop ?

Definition of a loopLoop is an highly important concept in programming.Indded, it allows you to repeat some operations agiven amount of time.

Loop typesIt exists 2 main type of loops :1. Repeating loops2. Conditional loops

Page 99: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

What is a loop ?

Definition of a loopLoop is an highly important concept in programming.Indded, it allows you to repeat some operations agiven amount of time.

Loop typesIt exists 2 main type of loops :1. Repeating loops2. Conditional loops

Page 100: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Outline

2. Loops2.1 What is it ?2.2 Repeating loop2.3 Conditional loop2.4 Stop a loop

Page 101: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Repeating loops

Why and how ?This kind of loop is what I will call the classical one.It allows you to repeat given operations from a startingvalue to an end value with specific increments.The syntax is the following :for i in range(starting_i,last_i,increment) :

What to repeatThe last value of a loop is exclusive (will not be used).If you don’t specify the value for the increment, it willuse the default one which is 1.ATTENTION : Don’t forget the indentation

Page 102: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Repeating loops

Repeating loops : First example

Python scriptfor i in range(0,6) :

print(i)

Result012345

Repeating loops : Second example

Python scriptfor i in range(0,6,2) :

print(i)

Result024

Page 103: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Repeating loops

Repeating loops : First example

Python scriptfor i in range(0,6) :

print(i)

Result012345

Repeating loops : Second example

Python scriptfor i in range(0,6,2) :

print(i)

Result024

Page 104: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Repeating loops

Repeating loops : First example

Python scriptfor i in range(0,6) :

print(i)

Result012345

Repeating loops : Second example

Python scriptfor i in range(0,6,2) :

print(i)

Result024

Page 105: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Repeating loops

Repeating loops : First example

Python scriptfor i in range(0,6) :

print(i)

Result012345

Repeating loops : Second example

Python scriptfor i in range(0,6,2) :

print(i)

Result024

Page 106: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Outline

2. Loops2.1 What is it ?2.2 Repeating loop2.3 Conditional loop2.4 Stop a loop

Page 107: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Conditional loops

The while loopThe aim of this loop is to repeat a part of the codeuntil a given condition is fulfill.The syntax is the following :while condition :

What_to_doATTENTION : If the condition is never fulfill,you will end up with an infinite loop and theprogram will never stop

Conditional loops : example

Python scripta=0while a<4 :

print(i)a=a+1

Result0123

Page 108: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Conditional loops

The while loopThe aim of this loop is to repeat a part of the codeuntil a given condition is fulfill.The syntax is the following :while condition :

What_to_doATTENTION : If the condition is never fulfill,you will end up with an infinite loop and theprogram will never stop

Conditional loops : example

Python scripta=0while a<4 :

print(i)a=a+1

Result0123

Page 109: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Conditional loops

The while loopThe aim of this loop is to repeat a part of the codeuntil a given condition is fulfill.The syntax is the following :while condition :

What_to_doATTENTION : If the condition is never fulfill,you will end up with an infinite loop and theprogram will never stop

Conditional loops : example

Python scripta=0while a<4 :

print(i)a=a+1

Result0123

Page 110: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Outline

2. Loops2.1 What is it ?2.2 Repeating loop2.3 Conditional loop2.4 Stop a loop

Page 111: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Stop a loop

The break statementThis statement aims at stopping a loop.The syntax is the following (assuming you are inside aloop) :break

break : example

Python scriptfor i in range(0,1000,2) :

print(i)if i>10 :

break

Result024681012

Page 112: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Stop a loop

The break statementThis statement aims at stopping a loop.The syntax is the following (assuming you are inside aloop) :break

break : example

Python scriptfor i in range(0,1000,2) :

print(i)if i>10 :

break

Result024681012

Page 113: Introduction to programmation using the Python language

Conditions and loops

Conditional StatementsWhat is it ?IndentationThe various conditional statements

LoopsWhat is it ?Repeating loopConditional loopStop a loop

Stop a loop

The break statementThis statement aims at stopping a loop.The syntax is the following (assuming you are inside aloop) :break

break : example

Python scriptfor i in range(0,1000,2) :

print(i)if i>10 :

break

Result024681012

Page 114: Introduction to programmation using the Python language

The notion of lists in Python

Page 115: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Outline

1. Introduction

2. Define a list

3. Some rules about lists

4. Create a list

5. Adding elements to a list

Page 116: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

What is a list ?

DefinitionLists in Python is something essential. Indeed, they areused to store several data in the same variable. Thisvariable is then called a list and contains severalelements, each of them characterized by a list-index.It is also possible to create list of lists.

Page 117: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Outline

1. Introduction

2. Define a list

3. Some rules about lists

4. Create a list

5. Adding elements to a list

Page 118: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

How a define a list ?

SyntaxThere is 2 ways to define an empty list :

▶ Either using the syntax :variable=list()▶ Or this one : variable=[ ]

Page 119: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Outline

1. Introduction

2. Define a list

3. Some rules about lists

4. Create a list

5. Adding elements to a list

Page 120: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

List Rules

Rules1. The first index of a list is always 02. A given element of a list should be called with ”[

]”. For example, if you want to access the 2nd

element of a list called list1, you should call it likethis : list1[1] (remember, the index of the firstelement is 0)

3. Don’t try to make additions directly of 2 lists(don’t write list3=list2+list1). If you want to doit, it is safer to make additions elements byelements

4. You can easily know the size (number ofelements) of a list using the len statement (forexample, len(list1) will render the number ofelements of the list list1)

Page 121: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Outline

1. Introduction

2. Define a list

3. Some rules about lists

4. Create a list

5. Adding elements to a list

Page 122: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Outline

4. Create a list4.1 Create a list with predefined values4.2 Create an empty list

Page 123: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

create a list with predefined values

How to do it ?To create a list from an already known set of values,the syntax is the following :list_name=[values_seperated_by_commas]

Example

Python scriptlist1=[0.1,0.2,0.3]print(list1)

Result[0.1,0.2,0.3]

Page 124: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

create a list with predefined values

How to do it ?To create a list from an already known set of values,the syntax is the following :list_name=[values_seperated_by_commas]

Example

Python scriptlist1=[0.1,0.2,0.3]print(list1)

Result[0.1,0.2,0.3]

Page 125: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

create a list with predefined values

How to do it ?To create a list from an already known set of values,the syntax is the following :list_name=[values_seperated_by_commas]

Example

Python scriptlist1=[0.1,0.2,0.3]print(list1)

Result[0.1,0.2,0.3]

Page 126: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Outline

4. Create a list4.1 Create a list with predefined values4.2 Create an empty list

Page 127: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

create an empty list

How to do it ?To create an empty list, the widely used syntax is thefollowing :list_name=[ ]

Example

Python scriptlist1=[ ]print(list1)

Result[ ]

Page 128: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

create an empty list

How to do it ?To create an empty list, the widely used syntax is thefollowing :list_name=[ ]

Example

Python scriptlist1=[ ]print(list1)

Result[ ]

Page 129: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

create an empty list

How to do it ?To create an empty list, the widely used syntax is thefollowing :list_name=[ ]

Example

Python scriptlist1=[ ]print(list1)

Result[ ]

Page 130: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Outline

1. Introduction

2. Define a list

3. Some rules about lists

4. Create a list

5. Adding elements to a list

Page 131: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Outline

5. Adding elements to a list5.1 At the end of a list5.2 Insert an element at a specific position5.3 List concatenation5.4 Remove an element5.5 Browse a list

Page 132: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Adding elements at the end of a list

How to do it ?This can be done by appending an existing list. Thesyntax is the following :list_name.append(new_value_to_add_at_the_end)

Example

Python scriptlist1=[ ]for i in range(0,4) :

list1.append(i)print(list1)

list1.append(4)print(list1)

Result[0,1,2,3]

[0,1,2,3,4]

Page 133: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Adding elements at the end of a list

How to do it ?This can be done by appending an existing list. Thesyntax is the following :list_name.append(new_value_to_add_at_the_end)

Example

Python scriptlist1=[ ]for i in range(0,4) :

list1.append(i)print(list1)

list1.append(4)print(list1)

Result[0,1,2,3]

[0,1,2,3,4]

Page 134: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Adding elements at the end of a list

How to do it ?This can be done by appending an existing list. Thesyntax is the following :list_name.append(new_value_to_add_at_the_end)

Example

Python scriptlist1=[ ]for i in range(0,4) :

list1.append(i)print(list1)

list1.append(4)print(list1)

Result[0,1,2,3]

[0,1,2,3,4]

Page 135: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Adding elements at the end of a list

How to do it ?This can be done by appending an existing list. Thesyntax is the following :list_name.append(new_value_to_add_at_the_end)

Example

Python scriptlist1=[ ]for i in range(0,4) :

list1.append(i)print(list1)list1.append(4)print(list1)

Result[0,1,2,3]

[0,1,2,3,4]

Page 136: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Adding elements at the end of a list

How to do it ?This can be done by appending an existing list. Thesyntax is the following :list_name.append(new_value_to_add_at_the_end)

Example

Python scriptlist1=[ ]for i in range(0,4) :

list1.append(i)print(list1)list1.append(4)print(list1)

Result[0,1,2,3][0,1,2,3,4]

Page 137: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Outline

5. Adding elements to a list5.1 At the end of a list5.2 Insert an element at a specific position5.3 List concatenation5.4 Remove an element5.5 Browse a list

Page 138: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Insert an element at a given position in thelist

How to do it ?To do it, one should use the insert function. Thesyntax is the following :list_name.insert(position,value)

Example

Python scripta=[0,1,2,4]print(a)

a.insert(3,3.0)print(a)

Result[0,1,2,4]

[0,1,2,3.0,4]

Page 139: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Insert an element at a given position in thelist

How to do it ?To do it, one should use the insert function. Thesyntax is the following :list_name.insert(position,value)

Example

Python scripta=[0,1,2,4]print(a)

a.insert(3,3.0)print(a)

Result[0,1,2,4]

[0,1,2,3.0,4]

Page 140: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Insert an element at a given position in thelist

How to do it ?To do it, one should use the insert function. Thesyntax is the following :list_name.insert(position,value)

Example

Python scripta=[0,1,2,4]print(a)

a.insert(3,3.0)print(a)

Result[0,1,2,4]

[0,1,2,3.0,4]

Page 141: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Insert an element at a given position in thelist

How to do it ?To do it, one should use the insert function. Thesyntax is the following :list_name.insert(position,value)

Example

Python scripta=[0,1,2,4]print(a)a.insert(3,3.0)print(a)

Result[0,1,2,4]

[0,1,2,3.0,4]

Page 142: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Insert an element at a given position in thelist

How to do it ?To do it, one should use the insert function. Thesyntax is the following :list_name.insert(position,value)

Example

Python scripta=[0,1,2,4]print(a)a.insert(3,3.0)print(a)

Result[0,1,2,4][0,1,2,3.0,4]

Page 143: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Outline

5. Adding elements to a list5.1 At the end of a list5.2 Insert an element at a specific position5.3 List concatenation5.4 Remove an element5.5 Browse a list

Page 144: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

List concatenation

How to do it ?There is 3 ways to it :1. The extend method :

list1.extend(list2)2. The ”+” method :

list1=list1+list23. The ”+=” method :

list1+=list2

Example extend method

Python scriptlist1=[0,1,2,3]list2=[4,5,6,7]list1.extend(list2)print(list1)

Result[0,1,2,3,4,5,6,7]

Page 145: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

List concatenation

How to do it ?There is 3 ways to it :1. The extend method :

list1.extend(list2)2. The ”+” method :

list1=list1+list23. The ”+=” method :

list1+=list2

Example extend method

Python scriptlist1=[0,1,2,3]list2=[4,5,6,7]list1.extend(list2)print(list1)

Result[0,1,2,3,4,5,6,7]

Page 146: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

List concatenation

How to do it ?There is 3 ways to it :1. The extend method :

list1.extend(list2)2. The ”+” method :

list1=list1+list23. The ”+=” method :

list1+=list2

Example extend method

Python scriptlist1=[0,1,2,3]list2=[4,5,6,7]list1.extend(list2)print(list1)

Result[0,1,2,3,4,5,6,7]

Page 147: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

List concatenation

How to do it ?There is 3 ways to it :1. The extend method :

list1.extend(list2)2. The ”+” method :

list1=list1+list23. The ”+=” method :

list1+=list2

Example ”+” method

Python scriptlist1=[0,1,2,3]list2=[4,5,6,7]list3=list1+list2print(list3)

Result[0,1,2,3,4,5,6,7]

Page 148: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

List concatenation

How to do it ?There is 3 ways to it :1. The extend method :

list1.extend(list2)2. The ”+” method :

list1=list1+list23. The ”+=” method :

list1+=list2

Example ”+” method

Python scriptlist1=[0,1,2,3]list2=[4,5,6,7]list3=list1+list2print(list3)

Result[0,1,2,3,4,5,6,7]

Page 149: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

List concatenation

How to do it ?There is 3 ways to it :1. The extend method :

list1.extend(list2)2. The ”+” method :

list1=list1+list23. The ”+=” method :

list1+=list2

Example ”+” method

Python scriptlist1=[0,1,2,3]list2=[4,5,6,7]list3=list1+list2print(list3)

Result[0,1,2,3,4,5,6,7]

Page 150: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

List concatenation

How to do it ?There is 3 ways to it :1. The extend method :

list1.extend(list2)2. The ”+” method :

list1=list1+list23. The ”+=” method :

list1+=list2

Example ”+=” method

Python scriptlist1=[0,1,2,3]list2=[4,5,6,7]list1+=listt2print(list1)

Result[0,1,2,3,4,5,6,7]

Page 151: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

List concatenation

How to do it ?There is 3 ways to it :1. The extend method :

list1.extend(list2)2. The ”+” method :

list1=list1+list23. The ”+=” method :

list1+=list2

Example ”+=” method

Python scriptlist1=[0,1,2,3]list2=[4,5,6,7]list1+=listt2print(list1)

Result[0,1,2,3,4,5,6,7]

Page 152: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

List concatenation

How to do it ?There is 3 ways to it :1. The extend method :

list1.extend(list2)2. The ”+” method :

list1=list1+list23. The ”+=” method :

list1+=list2

Example ”+=” method

Python scriptlist1=[0,1,2,3]list2=[4,5,6,7]list1+=listt2print(list1)

Result[0,1,2,3,4,5,6,7]

Page 153: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Outline

5. Adding elements to a list5.1 At the end of a list5.2 Insert an element at a specific position5.3 List concatenation5.4 Remove an element5.5 Browse a list

Page 154: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Remove an element of a list

How to do it ?There is 2 ways to it depending if you want to removean index or a value :

▶ If you want to remove an index :del list_name[index_to_remove]

▶ If you want to remove a value :list_name.remove(value_to_remove)It will only remove the value one time if itappears several times in the list.

Page 155: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Remove an element of a list

Example with del

Python scriptlist1=[0,1,2,3,1]list1.del[2]print(list1)

Result[0,1,3,1]

Example with remove

Python scriptlist1=[0,1,2,3,1]list1.remove(1)print(list1)

Result[0,2,3,1]

Page 156: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Remove an element of a list

Example with del

Python scriptlist1=[0,1,2,3,1]list1.del[2]print(list1)

Result[0,1,3,1]

Example with remove

Python scriptlist1=[0,1,2,3,1]list1.remove(1)print(list1)

Result[0,2,3,1]

Page 157: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Remove an element of a list

Example with del

Python scriptlist1=[0,1,2,3,1]list1.del[2]print(list1)

Result[0,1,3,1]

Example with remove

Python scriptlist1=[0,1,2,3,1]list1.remove(1)print(list1)

Result[0,2,3,1]

Page 158: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Remove an element of a list

Example with del

Python scriptlist1=[0,1,2,3,1]list1.del[2]print(list1)

Result[0,1,3,1]

Example with remove

Python scriptlist1=[0,1,2,3,1]list1.remove(1)print(list1)

Result[0,2,3,1]

Page 159: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Remove an element of a list

Example with del

Python scriptlist1=[0,1,2,3,1]list1.del[2]print(list1)

Result[0,1,3,1]

Example with remove

Python scriptlist1=[0,1,2,3,1]list1.remove(1)print(list1)

Result[0,2,3,1]

Page 160: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Outline

5. Adding elements to a list5.1 At the end of a list5.2 Insert an element at a specific position5.3 List concatenation5.4 Remove an element5.5 Browse a list

Page 161: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Browse a list

How to do it ?There is 2 ways to it :

▶ Using a loop starting from index 0 to the size ofthe list

▶ Using a loop over all the list elements

Example : index loop

Python scriptlist1=[0,1,2]for i in range(0,len(list1)) :

print(list1[i])

Result012

Page 162: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Browse a list

How to do it ?There is 2 ways to it :

▶ Using a loop starting from index 0 to the size ofthe list

▶ Using a loop over all the list elements

Example : index loop

Python scriptlist1=[0,1,2]for i in range(0,len(list1)) :

print(list1[i])

Result012

Page 163: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Browse a list

How to do it ?There is 2 ways to it :

▶ Using a loop starting from index 0 to the size ofthe list

▶ Using a loop over all the list elements

Example : index loop

Python scriptlist1=[0,1,2]for i in range(0,len(list1)) :

print(list1[i])

Result012

Page 164: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Browse a list

How to do it ?There is 2 ways to it :

▶ Using a loop starting from index 0 to the size ofthe list

▶ Using a loop over all the list elements

Example : loop over list elements

Python scriptlist1=[0,1,2]for i in list1 :

print(list1[i])

Result012

Page 165: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Browse a list

How to do it ?There is 2 ways to it :

▶ Using a loop starting from index 0 to the size ofthe list

▶ Using a loop over all the list elements

Example : loop over list elements

Python scriptlist1=[0,1,2]for i in list1 :

print(list1[i])

Result012

Page 166: Introduction to programmation using the Python language

Lists

Introduction

Define a list

Some rules about lists

Create a listCreate a list with predefined valuesCreate an empty list

Adding elements to a listAt the end of a listInsert an element at a specific positionList concatenationRemove an elementBrowse a list

Browse a list

How to do it ?There is 2 ways to it :

▶ Using a loop starting from index 0 to the size ofthe list

▶ Using a loop over all the list elements

Example : loop over list elements

Python scriptlist1=[0,1,2]for i in list1 :

print(list1[i])

Result012

Page 167: Introduction to programmation using the Python language

Reading and writing files

Page 168: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Outline

1. Reading files

2. Writing in a file

Page 169: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Outline

1. Reading files1.1 Introduction1.2 General philosophy1.3 One method for reading files

Page 170: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Why to read files ?

Why ?

▶ It is an extremely important concept in scientificprogramming

▶ Indeed, most of our calculation need input dataand it’s easier to read them from input files

▶ It is also of prime importance if you aim atpost-treatment program development

Page 171: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Why to read files ?

Why ?▶ It is an extremely important concept in scientific

programming

▶ Indeed, most of our calculation need input dataand it’s easier to read them from input files

▶ It is also of prime importance if you aim atpost-treatment program development

Page 172: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Why to read files ?

Why ?▶ It is an extremely important concept in scientific

programming▶ Indeed, most of our calculation need input data

and it’s easier to read them from input files

▶ It is also of prime importance if you aim atpost-treatment program development

Page 173: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Why to read files ?

Why ?▶ It is an extremely important concept in scientific

programming▶ Indeed, most of our calculation need input data

and it’s easier to read them from input files▶ It is also of prime importance if you aim at

post-treatment program development

Page 174: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Introduction

Advantages in Python

▶ Despite Python is an interpreted language andthus slower than compiled languages such as C orFortran, one of the main advantage of usingPython is that it’s quite easy to open and readfiles with it.

▶ Indeed, this task is quite difficult in Fortran and C▶ That’s why most of the post-treatment program

are written in both Python (for data extraction)and Fortran or C (for the calculation part).

Page 175: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Introduction

Advantages in Python▶ Despite Python is an interpreted language and

thus slower than compiled languages such as C orFortran, one of the main advantage of usingPython is that it’s quite easy to open and readfiles with it.

▶ Indeed, this task is quite difficult in Fortran and C▶ That’s why most of the post-treatment program

are written in both Python (for data extraction)and Fortran or C (for the calculation part).

Page 176: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Introduction

Advantages in Python▶ Despite Python is an interpreted language and

thus slower than compiled languages such as C orFortran, one of the main advantage of usingPython is that it’s quite easy to open and readfiles with it.

▶ Indeed, this task is quite difficult in Fortran and C

▶ That’s why most of the post-treatment programare written in both Python (for data extraction)and Fortran or C (for the calculation part).

Page 177: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Introduction

Advantages in Python▶ Despite Python is an interpreted language and

thus slower than compiled languages such as C orFortran, one of the main advantage of usingPython is that it’s quite easy to open and readfiles with it.

▶ Indeed, this task is quite difficult in Fortran and C▶ That’s why most of the post-treatment program

are written in both Python (for data extraction)and Fortran or C (for the calculation part).

Page 178: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Outline

1. Reading files1.1 Introduction1.2 General philosophy1.3 One method for reading files

Page 179: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Reading file in Python

Main idea▶ The idea is to browse an entire file and to store

its contains in a list, each of the list elementsbeing either a word or a line.

▶ This list will be then browsed in order to extractonly the informations that are relevant for theneeded calculation.

An essential ruleAttention : Whatever the method used, reading a filewill lead to string variable. Thus, one should notforget to convert them to integers or floating pointsbefore doing any calculation.

Page 180: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Reading file in Python

Main idea▶ The idea is to browse an entire file and to store

its contains in a list, each of the list elementsbeing either a word or a line.

▶ This list will be then browsed in order to extractonly the informations that are relevant for theneeded calculation.

An essential ruleAttention : Whatever the method used, reading a filewill lead to string variable. Thus, one should notforget to convert them to integers or floating pointsbefore doing any calculation.

Page 181: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Reading file in Python

Main idea▶ The idea is to browse an entire file and to store

its contains in a list, each of the list elementsbeing either a word or a line.

▶ This list will be then browsed in order to extractonly the informations that are relevant for theneeded calculation.

An essential ruleAttention : Whatever the method used, reading a filewill lead to string variable. Thus, one should notforget to convert them to integers or floating pointsbefore doing any calculation.

Page 182: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Reading file in Python

Main idea▶ The idea is to browse an entire file and to store

its contains in a list, each of the list elementsbeing either a word or a line.

▶ This list will be then browsed in order to extractonly the informations that are relevant for theneeded calculation.

An essential ruleAttention : Whatever the method used, reading a filewill lead to string variable. Thus, one should notforget to convert them to integers or floating pointsbefore doing any calculation.

Page 183: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Outline

1. Reading files1.1 Introduction1.2 General philosophy1.3 One method for reading files

Page 184: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

The open method

What is it ?This method for reading files is based on the openintrinsic Python function.

Page 185: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

The open method : How ?

The modus operandi

1. Apply the function open with its readlinesfunctionality to a file

2. Store the result in a list.

Page 186: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

The open method : How ?

The modus operandi1. Apply the function open with its readlines

functionality to a file

2. Store the result in a list.

Page 187: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

The open method : How ?

The modus operandi1. Apply the function open with its readlines

functionality to a file2. Store the result in a list.

Page 188: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

First example

The ”test” file1 2 3 4 56 7 8 9 1011 12 13 14

First example

Python scriptf=open(”test”).readlines()print(f)

Result[1 2 3 4 5 \n,6 7 89 10 \n, 11 12 1314]

Thus, each of the list element are lines. So howto create lists with only words and not lines.

Page 189: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

First example

The ”test” file1 2 3 4 56 7 8 9 1011 12 13 14

First example

Python scriptf=open(”test”).readlines()print(f)

Result[1 2 3 4 5 \n,6 7 89 10 \n, 11 12 1314]

Thus, each of the list element are lines. So howto create lists with only words and not lines.

Page 190: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

First example

The ”test” file1 2 3 4 56 7 8 9 1011 12 13 14

First example

Python scriptf=open(”test”).readlines()print(f)

Result[1 2 3 4 5 \n,6 7 89 10 \n, 11 12 1314]

Thus, each of the list element are lines. So howto create lists with only words and not lines.

Page 191: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

First example

The ”test” file1 2 3 4 56 7 8 9 1011 12 13 14

First example

Python scriptf=open(”test”).readlines()print(f)

Result[1 2 3 4 5 \n,6 7 89 10 \n, 11 12 1314]

Thus, each of the list element are lines. So howto create lists with only words and not lines.

Page 192: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Splitting lines into words

the str.split methodWe would like now to read a file and store it as a listof lists, each of the lists being a line and each of thelists elements words.For this, we can use the str.split functionality.

Page 193: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

str.split example

The ”test” file1 2 3 4 56 7 8 9 1011 12 13 14

str.split example

Python scriptl1=[ ]f=open(”test”).readlines()# browse each linefor i in range(0,len(f)) :

l2=[ ]# browse each word of the line

for j in range(0,len(str.split(f[i]))) :l2.append(str.split(f[i])[j])

l1.append(l2)

Result[[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14]]

Page 194: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

str.split example

The ”test” file1 2 3 4 56 7 8 9 1011 12 13 14

str.split example

Python scriptl1=[ ]f=open(”test”).readlines()# browse each linefor i in range(0,len(f)) :

l2=[ ]# browse each word of the line

for j in range(0,len(str.split(f[i]))) :l2.append(str.split(f[i])[j])

l1.append(l2)

Result[[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14]]

Page 195: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

str.split example

The ”test” file1 2 3 4 56 7 8 9 1011 12 13 14

str.split example

Python scriptl1=[ ]f=open(”test”).readlines()# browse each linefor i in range(0,len(f)) :

l2=[ ]# browse each word of the line

for j in range(0,len(str.split(f[i]))) :l2.append(str.split(f[i])[j])

l1.append(l2)

Result[[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14]]

Page 196: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Outline

1. Reading files

2. Writing in a file

Page 197: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Writing in a file

How ?This is based on the use of the intrinsic write Pythonfunction

line breakThis is done by writing : ’\n’

Page 198: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Writing in a file

modus operandi

1. Call the open function on a new file and the ”w”format

2. Write inside everything you want using thefunctionality write

3. Close the file with the functionality close

Page 199: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Writing in a file

modus operandi1. Call the open function on a new file and the ”w”

format

2. Write inside everything you want using thefunctionality write

3. Close the file with the functionality close

Page 200: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Writing in a file

modus operandi1. Call the open function on a new file and the ”w”

format2. Write inside everything you want using the

functionality write

3. Close the file with the functionality close

Page 201: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Writing in a file

modus operandi1. Call the open function on a new file and the ”w”

format2. Write inside everything you want using the

functionality write3. Close the file with the functionality close

Page 202: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Writing files : Example

First example

Python scripta=[[First,line],[Second,line]]f=open(”test”,”w”)for i in range(0,len(a)) :

for j in range(0,len(a[i]) :f.write(a[i][j])

f.write(”\n”)f.close()

File ”test”First lineSecond line

Page 203: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Writing files : Example

First example

Python scripta=[[First,line],[Second,line]]f=open(”test”,”w”)for i in range(0,len(a)) :

for j in range(0,len(a[i]) :f.write(a[i][j])

f.write(”\n”)f.close()

File ”test”First lineSecond line

Page 204: Introduction to programmation using the Python language

Read and write

Reading filesIntroductionGeneral philosophyOne method

Writing in a file

Writing files : Example

First example

Python scripta=[[First,line],[Second,line]]f=open(”test”,”w”)for i in range(0,len(a)) :

for j in range(0,len(a[i]) :f.write(a[i][j])

f.write(”\n”)f.close()

File ”test”First lineSecond line

Page 205: Introduction to programmation using the Python language

The Numpy module

Page 206: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Outline

1. Présentation

2. Trigonometric functions

3. Matrices

4. Solve Equation system

Page 207: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

The Numpy module : Presentation

What is it ?This module allows you to

▶ Use trigonometric functions▶ Make some calculations on matrices▶ Solve equations systems

Page 208: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Outline

1. Présentation

2. Trigonometric functions

3. Matrices

4. Solve Equation system

Page 209: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Numpy : Trigonometric functions

Which of them ?▶ Cosine (numpy.cos) et Arccos (numpy.arccos)▶ Sinus (numpy.sin) et Arcsin (numpy.arcsin)▶ Tangent (numpy.tan) et Arctan (numpy.arctan)

Attention : These functions are all in radian (It existthe function numpy.pi for the pi number)

Page 210: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Numpy : Trigonometric functions

Which of them ?▶ Cosine (numpy.cos) et Arccos (numpy.arccos)▶ Sinus (numpy.sin) et Arcsin (numpy.arcsin)▶ Tangent (numpy.tan) et Arctan (numpy.arctan)

Attention : These functions are all in radian (It existthe function numpy.pi for the pi number)

Page 211: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Numpy : Trigonometric functions

Which of them ?▶ Cosine (numpy.cos) et Arccos (numpy.arccos)▶ Sinus (numpy.sin) et Arcsin (numpy.arcsin)▶ Tangent (numpy.tan) et Arctan (numpy.arctan)

Attention : These functions are all in radian (It existthe function numpy.pi for the pi number)

Page 212: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Numpy : Trigonometric functions

Example

Python scriptimport numpy as npa=0.0b=np.pi/2.0c=np.pi/3.0print(a,b,c)

cosa=np.cos(a)cosb=np.cos(b)cosc=np.cos(c)print(np.arccos(cosa))print(np.arccos(cosb))print(np.arccos(cosc))

Result0.0 1.57 1.04

1.0 6.12e-17 0.500.01.5701.04

Page 213: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Numpy : Trigonometric functions

Example

Python scriptimport numpy as npa=0.0b=np.pi/2.0c=np.pi/3.0print(a,b,c)

cosa=np.cos(a)cosb=np.cos(b)cosc=np.cos(c)print(np.arccos(cosa))print(np.arccos(cosb))print(np.arccos(cosc))

Result0.0 1.57 1.04

1.0 6.12e-17 0.500.01.5701.04

Page 214: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Numpy : Trigonometric functions

Example

Python scriptimport numpy as npa=0.0b=np.pi/2.0c=np.pi/3.0print(a,b,c)

cosa=np.cos(a)cosb=np.cos(b)cosc=np.cos(c)print(np.arccos(cosa))print(np.arccos(cosb))print(np.arccos(cosc))

Result0.0 1.57 1.04

1.0 6.12e-17 0.500.01.5701.04

Page 215: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Numpy : Trigonometric functions

Example

Python scriptimport numpy as npa=0.0b=np.pi/2.0c=np.pi/3.0print(a,b,c)cosa=np.cos(a)cosb=np.cos(b)cosc=np.cos(c)

print(np.arccos(cosa))print(np.arccos(cosb))print(np.arccos(cosc))

Result0.0 1.57 1.04

1.0 6.12e-17 0.500.01.5701.04

Page 216: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Numpy : Trigonometric functions

Example

Python scriptimport numpy as npa=0.0b=np.pi/2.0c=np.pi/3.0print(a,b,c)cosa=np.cos(a)cosb=np.cos(b)cosc=np.cos(c)

print(np.arccos(cosa))print(np.arccos(cosb))print(np.arccos(cosc))

Result0.0 1.57 1.041.0 6.12e-17 0.50

0.01.5701.04

Page 217: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Numpy : Trigonometric functions

Example

Python scriptimport numpy as npa=0.0b=np.pi/2.0c=np.pi/3.0print(a,b,c)cosa=np.cos(a)cosb=np.cos(b)cosc=np.cos(c)print(np.arccos(cosa))print(np.arccos(cosb))print(np.arccos(cosc))

Result0.0 1.57 1.041.0 6.12e-17 0.50

0.01.5701.04

Page 218: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Numpy : Trigonometric functions

Example

Python scriptimport numpy as npa=0.0b=np.pi/2.0c=np.pi/3.0print(a,b,c)cosa=np.cos(a)cosb=np.cos(b)cosc=np.cos(c)print(np.arccos(cosa))print(np.arccos(cosb))print(np.arccos(cosc))

Result0.0 1.57 1.041.0 6.12e-17 0.500.01.5701.04

Page 219: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Outline

1. Présentation

2. Trigonometric functions

3. Matrices

4. Solve Equation system

Page 220: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Outline

3. Matrices3.1 Create Matrices and vectors3.2 Scalar product3.3 Matrices product3.4 Transpose matrix3.5 Matrix determinant3.6 Matrix inversion

Page 221: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create vectors with zeros

The numpy.zeros functionThis function of the Numpy module allows to createzeros floating points vectors (or matrices) of specificsizes

Syntax : a=numpi.zeros(m)a will be a zeros vector of size m

Example

Python scriptimport numpy as npa=np.zeros(4)print(a)

Result[0. 0. 0. 0.]

Page 222: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create vectors with zeros

The numpy.zeros functionThis function of the Numpy module allows to createzeros floating points vectors (or matrices) of specificsizes

Syntax : a=numpi.zeros(m)a will be a zeros vector of size m

Example

Python scriptimport numpy as npa=np.zeros(4)print(a)

Result[0. 0. 0. 0.]

Page 223: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create vectors with zeros

The numpy.zeros functionThis function of the Numpy module allows to createzeros floating points vectors (or matrices) of specificsizesSyntax : a=numpi.zeros(m)a will be a zeros vector of size m

Example

Python scriptimport numpy as npa=np.zeros(4)print(a)

Result[0. 0. 0. 0.]

Page 224: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create vectors with zeros

The numpy.zeros functionThis function of the Numpy module allows to createzeros floating points vectors (or matrices) of specificsizesSyntax : a=numpi.zeros(m)a will be a zeros vector of size m

Example

Python scriptimport numpy as npa=np.zeros(4)print(a)

Result[0. 0. 0. 0.]

Page 225: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create vectors with zeros

The numpy.zeros functionThis function of the Numpy module allows to createzeros floating points vectors (or matrices) of specificsizesSyntax : a=numpi.zeros(m)a will be a zeros vector of size m

Example

Python scriptimport numpy as npa=np.zeros(4)print(a)

Result[0. 0. 0. 0.]

Page 226: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create vectors with given values

The numpy.array functionThis function allows to create vectors (or matrices)from an already known series of values

Syntax : a=numpi.array([values]).Each values should be separated by comas.a will be a vector that contains the given values

Example

Python scriptimport numpy as npa=np.array([1.0,1.1,1.2])print(a)

Result[1.0 1.1 1.2]

Page 227: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create vectors with given values

The numpy.array functionThis function allows to create vectors (or matrices)from an already known series of values

Syntax : a=numpi.array([values]).Each values should be separated by comas.a will be a vector that contains the given values

Example

Python scriptimport numpy as npa=np.array([1.0,1.1,1.2])print(a)

Result[1.0 1.1 1.2]

Page 228: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create vectors with given values

The numpy.array functionThis function allows to create vectors (or matrices)from an already known series of valuesSyntax : a=numpi.array([values]).Each values should be separated by comas.a will be a vector that contains the given values

Example

Python scriptimport numpy as npa=np.array([1.0,1.1,1.2])print(a)

Result[1.0 1.1 1.2]

Page 229: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create vectors with given values

The numpy.array functionThis function allows to create vectors (or matrices)from an already known series of valuesSyntax : a=numpi.array([values]).Each values should be separated by comas.a will be a vector that contains the given values

Example

Python scriptimport numpy as npa=np.array([1.0,1.1,1.2])print(a)

Result[1.0 1.1 1.2]

Page 230: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create vectors with given values

The numpy.array functionThis function allows to create vectors (or matrices)from an already known series of valuesSyntax : a=numpi.array([values]).Each values should be separated by comas.a will be a vector that contains the given values

Example

Python scriptimport numpy as npa=np.array([1.0,1.1,1.2])print(a)

Result[1.0 1.1 1.2]

Page 231: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create matrices with zeros

The numpy.zeros functionThis function of the Numpy module allows to createzeros floating points vectors (or matrices) of specificsizes

Syntax : a=numpi.zeros((m,n)).a will be a zeros matrix of size m by n

Example

Python scriptimport numpy as npa=np.zeros((2,3))print(a)

Result[[0. 0. 0.][0. 0. 0.]]

Page 232: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create matrices with zeros

The numpy.zeros functionThis function of the Numpy module allows to createzeros floating points vectors (or matrices) of specificsizes

Syntax : a=numpi.zeros((m,n)).a will be a zeros matrix of size m by n

Example

Python scriptimport numpy as npa=np.zeros((2,3))print(a)

Result[[0. 0. 0.][0. 0. 0.]]

Page 233: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create matrices with zeros

The numpy.zeros functionThis function of the Numpy module allows to createzeros floating points vectors (or matrices) of specificsizesSyntax : a=numpi.zeros((m,n)).a will be a zeros matrix of size m by n

Example

Python scriptimport numpy as npa=np.zeros((2,3))print(a)

Result[[0. 0. 0.][0. 0. 0.]]

Page 234: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create matrices with zeros

The numpy.zeros functionThis function of the Numpy module allows to createzeros floating points vectors (or matrices) of specificsizesSyntax : a=numpi.zeros((m,n)).a will be a zeros matrix of size m by n

Example

Python scriptimport numpy as npa=np.zeros((2,3))print(a)

Result[[0. 0. 0.][0. 0. 0.]]

Page 235: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create matrices with zeros

The numpy.zeros functionThis function of the Numpy module allows to createzeros floating points vectors (or matrices) of specificsizesSyntax : a=numpi.zeros((m,n)).a will be a zeros matrix of size m by n

Example

Python scriptimport numpy as npa=np.zeros((2,3))print(a)

Result[[0. 0. 0.][0. 0. 0.]]

Page 236: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create matrices with given values

The numpy.array functionThis function allows to create vectors (or matrices)from an already known series of values

Syntax : a=numpi.array([[values1],[values2]).Each values should be separated by comas.a will be a 2 line matrix containing the given values

Example

Python scriptimport numpy as npa=np.array([[1.0,1.1,1.2],[2.0,2.1,2.2]])print(a)

Result[[1.2 1.1 1.2][2.0 2.1 2.2]]

Page 237: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create matrices with given values

The numpy.array functionThis function allows to create vectors (or matrices)from an already known series of values

Syntax : a=numpi.array([[values1],[values2]).Each values should be separated by comas.a will be a 2 line matrix containing the given values

Example

Python scriptimport numpy as npa=np.array([[1.0,1.1,1.2],[2.0,2.1,2.2]])print(a)

Result[[1.2 1.1 1.2][2.0 2.1 2.2]]

Page 238: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create matrices with given values

The numpy.array functionThis function allows to create vectors (or matrices)from an already known series of valuesSyntax : a=numpi.array([[values1],[values2]).Each values should be separated by comas.a will be a 2 line matrix containing the given values

Example

Python scriptimport numpy as npa=np.array([[1.0,1.1,1.2],[2.0,2.1,2.2]])print(a)

Result[[1.2 1.1 1.2][2.0 2.1 2.2]]

Page 239: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create matrices with given values

The numpy.array functionThis function allows to create vectors (or matrices)from an already known series of valuesSyntax : a=numpi.array([[values1],[values2]).Each values should be separated by comas.a will be a 2 line matrix containing the given values

Example

Python scriptimport numpy as npa=np.array([[1.0,1.1,1.2],[2.0,2.1,2.2]])print(a)

Result[[1.2 1.1 1.2][2.0 2.1 2.2]]

Page 240: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Create matrices with given values

The numpy.array functionThis function allows to create vectors (or matrices)from an already known series of valuesSyntax : a=numpi.array([[values1],[values2]).Each values should be separated by comas.a will be a 2 line matrix containing the given values

Example

Python scriptimport numpy as npa=np.array([[1.0,1.1,1.2],[2.0,2.1,2.2]])print(a)

Result[[1.2 1.1 1.2][2.0 2.1 2.2]]

Page 241: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Outline

3. Matrices3.1 Create Matrices and vectors3.2 Scalar product3.3 Matrices product3.4 Transpose matrix3.5 Matrix determinant3.6 Matrix inversion

Page 242: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Scalar product

numpy.dotThis Numpy function allows to compute scalar productbetween 2 vectors

Syntaxc=numpy.dot(a,b)c will be a scalar, result of the scalar product of a byb.

Example

Python scriptimport numpy as npa=np.array([1,2,3])b=[4,5,6]c=np.dot(a,b)print(c)

Result32

Page 243: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Scalar product

numpy.dotThis Numpy function allows to compute scalar productbetween 2 vectors

Syntaxc=numpy.dot(a,b)c will be a scalar, result of the scalar product of a byb.

Example

Python scriptimport numpy as npa=np.array([1,2,3])b=[4,5,6]c=np.dot(a,b)print(c)

Result32

Page 244: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Scalar product

numpy.dotThis Numpy function allows to compute scalar productbetween 2 vectors

Syntaxc=numpy.dot(a,b)c will be a scalar, result of the scalar product of a byb.

Example

Python scriptimport numpy as npa=np.array([1,2,3])b=[4,5,6]c=np.dot(a,b)print(c)

Result32

Page 245: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Scalar product

numpy.dotThis Numpy function allows to compute scalar productbetween 2 vectors

Syntaxc=numpy.dot(a,b)c will be a scalar, result of the scalar product of a byb.

Example

Python scriptimport numpy as npa=np.array([1,2,3])b=[4,5,6]c=np.dot(a,b)print(c)

Result32

Page 246: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Scalar product

numpy.dotThis Numpy function allows to compute scalar productbetween 2 vectors

Syntaxc=numpy.dot(a,b)c will be a scalar, result of the scalar product of a byb.

Example

Python scriptimport numpy as npa=np.array([1,2,3])b=[4,5,6]c=np.dot(a,b)print(c)

Result32

Page 247: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Outline

3. Matrices3.1 Create Matrices and vectors3.2 Scalar product3.3 Matrices product3.4 Transpose matrix3.5 Matrix determinant3.6 Matrix inversion

Page 248: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Produit matriciel

numpy.dotThis Numpy function allows also to multiply matrices.

Syntaxc=numpy.dot(a,b).c is a matrix that the result of the multiplication of apar b

Example

Python scriptimport numpy as npa=np.array([[1,2,3],[4,5,6]])c=np.array([[4],[2],[1]])print(np.dot(a,c))

Result[[11][32]]

Page 249: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Produit matriciel

numpy.dotThis Numpy function allows also to multiply matrices.

Syntaxc=numpy.dot(a,b).c is a matrix that the result of the multiplication of apar b

Example

Python scriptimport numpy as npa=np.array([[1,2,3],[4,5,6]])c=np.array([[4],[2],[1]])print(np.dot(a,c))

Result[[11][32]]

Page 250: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Produit matriciel

numpy.dotThis Numpy function allows also to multiply matrices.

Syntaxc=numpy.dot(a,b).c is a matrix that the result of the multiplication of apar b

Example

Python scriptimport numpy as npa=np.array([[1,2,3],[4,5,6]])c=np.array([[4],[2],[1]])print(np.dot(a,c))

Result[[11][32]]

Page 251: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Produit matriciel

numpy.dotThis Numpy function allows also to multiply matrices.

Syntaxc=numpy.dot(a,b).c is a matrix that the result of the multiplication of apar b

Example

Python scriptimport numpy as npa=np.array([[1,2,3],[4,5,6]])c=np.array([[4],[2],[1]])print(np.dot(a,c))

Result[[11][32]]

Page 252: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Produit matriciel

numpy.dotThis Numpy function allows also to multiply matrices.

Syntaxc=numpy.dot(a,b).c is a matrix that the result of the multiplication of apar b

Example

Python scriptimport numpy as npa=np.array([[1,2,3],[4,5,6]])c=np.array([[4],[2],[1]])print(np.dot(a,c))

Result[[11][32]]

Page 253: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Outline

3. Matrices3.1 Create Matrices and vectors3.2 Scalar product3.3 Matrices product3.4 Transpose matrix3.5 Matrix determinant3.6 Matrix inversion

Page 254: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Transpose matrix

.TThis numpy function allows to transpose matrices.

Syntaxc=a.Tc is the transpose matrix of a

Example

Python scriptimport numpy as npa=np.array([[1,2,3],[4,5,6]])print(a)

print(a.T)

Result[[1 2 3][4 5 6]]

[[1 4][2 4][3 6]]

Page 255: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Transpose matrix

.TThis numpy function allows to transpose matrices.

Syntaxc=a.Tc is the transpose matrix of a

Example

Python scriptimport numpy as npa=np.array([[1,2,3],[4,5,6]])print(a)

print(a.T)

Result[[1 2 3][4 5 6]]

[[1 4][2 4][3 6]]

Page 256: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Transpose matrix

.TThis numpy function allows to transpose matrices.

Syntaxc=a.Tc is the transpose matrix of a

Example

Python scriptimport numpy as npa=np.array([[1,2,3],[4,5,6]])print(a)

print(a.T)

Result[[1 2 3][4 5 6]]

[[1 4][2 4][3 6]]

Page 257: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Transpose matrix

.TThis numpy function allows to transpose matrices.

Syntaxc=a.Tc is the transpose matrix of a

Example

Python scriptimport numpy as npa=np.array([[1,2,3],[4,5,6]])print(a)

print(a.T)

Result[[1 2 3][4 5 6]]

[[1 4][2 4][3 6]]

Page 258: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Transpose matrix

.TThis numpy function allows to transpose matrices.

Syntaxc=a.Tc is the transpose matrix of a

Example

Python scriptimport numpy as npa=np.array([[1,2,3],[4,5,6]])print(a)

print(a.T)

Result[[1 2 3][4 5 6]]

[[1 4][2 4][3 6]]

Page 259: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Transpose matrix

.TThis numpy function allows to transpose matrices.

Syntaxc=a.Tc is the transpose matrix of a

Example

Python scriptimport numpy as npa=np.array([[1,2,3],[4,5,6]])print(a)print(a.T)

Result[[1 2 3][4 5 6]]

[[1 4][2 4][3 6]]

Page 260: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Transpose matrix

.TThis numpy function allows to transpose matrices.

Syntaxc=a.Tc is the transpose matrix of a

Example

Python scriptimport numpy as npa=np.array([[1,2,3],[4,5,6]])print(a)print(a.T)

Result[[1 2 3][4 5 6]][[1 4][2 4][3 6]]

Page 261: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Outline

3. Matrices3.1 Create Matrices and vectors3.2 Scalar product3.3 Matrices product3.4 Transpose matrix3.5 Matrix determinant3.6 Matrix inversion

Page 262: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Matrix determinant

numpy.linalg.detThis numpy function allows to compute thedeterminant of a matrix.

Syntaxc=numpy.linalg.det(a)c will be the determinant of the squared matrix a.

Example

Python scriptimport numpy as npfrom numpy.linalg import deta=np.array([[1,2],[3,4]])print(det(a))

Result-2.00

Page 263: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Matrix determinant

numpy.linalg.detThis numpy function allows to compute thedeterminant of a matrix.

Syntaxc=numpy.linalg.det(a)c will be the determinant of the squared matrix a.

Example

Python scriptimport numpy as npfrom numpy.linalg import deta=np.array([[1,2],[3,4]])print(det(a))

Result-2.00

Page 264: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Matrix determinant

numpy.linalg.detThis numpy function allows to compute thedeterminant of a matrix.

Syntaxc=numpy.linalg.det(a)c will be the determinant of the squared matrix a.

Example

Python scriptimport numpy as npfrom numpy.linalg import deta=np.array([[1,2],[3,4]])print(det(a))

Result-2.00

Page 265: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Matrix determinant

numpy.linalg.detThis numpy function allows to compute thedeterminant of a matrix.

Syntaxc=numpy.linalg.det(a)c will be the determinant of the squared matrix a.

Example

Python scriptimport numpy as npfrom numpy.linalg import deta=np.array([[1,2],[3,4]])print(det(a))

Result-2.00

Page 266: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Matrix determinant

numpy.linalg.detThis numpy function allows to compute thedeterminant of a matrix.

Syntaxc=numpy.linalg.det(a)c will be the determinant of the squared matrix a.

Example

Python scriptimport numpy as npfrom numpy.linalg import deta=np.array([[1,2],[3,4]])print(det(a))

Result-2.00

Page 267: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Outline

3. Matrices3.1 Create Matrices and vectors3.2 Scalar product3.3 Matrices product3.4 Transpose matrix3.5 Matrix determinant3.6 Matrix inversion

Page 268: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Matrix inversion

numpy.linalg.invTis Numpy function allows to invert squared matrix.

Syntaxc=numpy.linalg.inv(a)c will be the inverted a matrix.

Example

Python scriptimport numpy as npfrom numpy.linalg import inva=np.array([[1,2],[3,4]])print(inv(a))

Result[[−2.00 1.0][1.5 − 0.5]]

Page 269: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Matrix inversion

numpy.linalg.invTis Numpy function allows to invert squared matrix.

Syntaxc=numpy.linalg.inv(a)c will be the inverted a matrix.

Example

Python scriptimport numpy as npfrom numpy.linalg import inva=np.array([[1,2],[3,4]])print(inv(a))

Result[[−2.00 1.0][1.5 − 0.5]]

Page 270: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Matrix inversion

numpy.linalg.invTis Numpy function allows to invert squared matrix.

Syntaxc=numpy.linalg.inv(a)c will be the inverted a matrix.

Example

Python scriptimport numpy as npfrom numpy.linalg import inva=np.array([[1,2],[3,4]])print(inv(a))

Result[[−2.00 1.0][1.5 − 0.5]]

Page 271: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Matrix inversion

numpy.linalg.invTis Numpy function allows to invert squared matrix.

Syntaxc=numpy.linalg.inv(a)c will be the inverted a matrix.

Example

Python scriptimport numpy as npfrom numpy.linalg import inva=np.array([[1,2],[3,4]])print(inv(a))

Result[[−2.00 1.0][1.5 − 0.5]]

Page 272: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Matrix inversion

numpy.linalg.invTis Numpy function allows to invert squared matrix.

Syntaxc=numpy.linalg.inv(a)c will be the inverted a matrix.

Example

Python scriptimport numpy as npfrom numpy.linalg import inva=np.array([[1,2],[3,4]])print(inv(a))

Result[[−2.00 1.0][1.5 − 0.5]]

Page 273: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Outline

1. Présentation

2. Trigonometric functions

3. Matrices

4. Solve Equation system

Page 274: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Outline

4. Solve Equation system4.1 Linear equation system4.2 Matrix diagonalization

Page 275: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Linear equation system

numpy.linalg.solveThis Numpy function allows to solve linear equationsystems.

Syntaxec=numpy.linalg.solve(a,b) where a is the coefficientmatrix and b a vector.

Page 276: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Linear equation system

numpy.linalg.solveThis Numpy function allows to solve linear equationsystems.

Syntaxec=numpy.linalg.solve(a,b) where a is the coefficientmatrix and b a vector.

Page 277: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Linear equation system

numpy.linalg.solveThis Numpy function allows to solve linear equationsystems.

Syntaxec=numpy.linalg.solve(a,b) where a is the coefficientmatrix and b a vector.

Page 278: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Solve Equation system

ExampleLets solve the linear equation system{

3x + y = 9x + 2y = 8

Python scriptimport numpy as npfrom numpy.linalg import solvea=np.array([[3,1],[1,2]])b=np.array([9,8])print(solve(a,b))

Result[2 3]

Solutions are x=2 and y=3

Page 279: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Solve Equation system

ExampleLets solve the linear equation system{

3x + y = 9x + 2y = 8

Python scriptimport numpy as npfrom numpy.linalg import solvea=np.array([[3,1],[1,2]])b=np.array([9,8])print(solve(a,b))

Result[2 3]

Solutions are x=2 and y=3

Page 280: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Solve Equation system

ExampleLets solve the linear equation system{

3x + y = 9x + 2y = 8

Python scriptimport numpy as npfrom numpy.linalg import solvea=np.array([[3,1],[1,2]])b=np.array([9,8])print(solve(a,b))

Result[2 3]

Solutions are x=2 and y=3

Page 281: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Solve Equation system

ExampleLets solve the linear equation system{

3x + y = 9x + 2y = 8

Python scriptimport numpy as npfrom numpy.linalg import solvea=np.array([[3,1],[1,2]])b=np.array([9,8])print(solve(a,b))

Result[2 3]

Solutions are x=2 and y=3

Page 282: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Outline

4. Solve Equation system4.1 Linear equation system4.2 Matrix diagonalization

Page 283: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Matrix diagonalization

numpy.linalg.eigThis Numpy function will output the eigenvalues andeigenvectors of a matrix

SyntaxE, V=numpy.linalg.eig(a)E will contain the eigenvalues of a and V itseigenvectors.

Page 284: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Matrix diagonalization

numpy.linalg.eigThis Numpy function will output the eigenvalues andeigenvectors of a matrix

SyntaxE, V=numpy.linalg.eig(a)E will contain the eigenvalues of a and V itseigenvectors.

Page 285: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Matrix diagonalization

numpy.linalg.eigThis Numpy function will output the eigenvalues andeigenvectors of a matrix

SyntaxE, V=numpy.linalg.eig(a)E will contain the eigenvalues of a and V itseigenvectors.

Page 286: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Matrix diagonalization

Example

Python scriptimport numpy as npfrom numpy.linalg import eigA=np.array([[1,1,-2],[-1,2,1],[0,1,-1]])D, V = eig(A)print(D)

Result[2. 1. -1.]

[[3.015e − 01 −8.017e −01 7.071e − 01][9.045e − 01 −5.345e −01 2.435e − 17][3.015e − 01 −2.672e −01 7.071e − 01]]

Page 287: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Matrix diagonalization

Example

Python scriptimport numpy as npfrom numpy.linalg import eigA=np.array([[1,1,-2],[-1,2,1],[0,1,-1]])D, V = eig(A)print(D)

Result[2. 1. -1.]

[[3.015e − 01 −8.017e −01 7.071e − 01][9.045e − 01 −5.345e −01 2.435e − 17][3.015e − 01 −2.672e −01 7.071e − 01]]

Page 288: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Matrix diagonalization

Example

Python scriptimport numpy as npfrom numpy.linalg import eigA=np.array([[1,1,-2],[-1,2,1],[0,1,-1]])D, V = eig(A)print(D)

Result[2. 1. -1.]

[[3.015e − 01 −8.017e −01 7.071e − 01][9.045e − 01 −5.345e −01 2.435e − 17][3.015e − 01 −2.672e −01 7.071e − 01]]

Page 289: Introduction to programmation using the Python language

The Numpy module

Présentation

Trigonometric functions

MatricesCreate Matrices and vectorsScalar productMatrices productTranspose matrixMatrix determinantMatrix inversion

Equation systemLinear equation systemMatrix diagonalization

Matrix diagonalization

Example

Python scriptimport numpy as npfrom numpy.linalg import eigA=np.array([[1,1,-2],[-1,2,1],[0,1,-1]])D, V = eig(A)print(D)

Result[2. 1. -1.][[3.015e − 01 −8.017e −01 7.071e − 01][9.045e − 01 −5.345e −01 2.435e − 17][3.015e − 01 −2.672e −01 7.071e − 01]]

Page 290: Introduction to programmation using the Python language

Graphical representationThe matplotlib module

Page 291: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Outline

1. Introduction

2. 2D plots

3. Multiple plots

4. Titles

5. Legend

6. Axis range

Page 292: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Outline

1. Introduction1.1 Definition1.2 Structure of a program

Page 293: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Definition

Matplotlib : What is it ?Matplotlib is a Python module which, combined withthe Numpy and Scipy module, is an extremelypowerful tools for plotting and visualizing data .The Matplotlib module have several advantages :

▶ free of charge▶ easy to use▶ extensible▶ One of the biggest developer community▶ etc

Page 294: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Outline

1. Introduction1.1 Definition1.2 Structure of a program

Page 295: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Structure of a program

Structure d’un programmeA program with plot is most athe structured in the followingfashion :

1. Import the pyplotfunctionality of matplotlib

2. The program part thatmake the calculations

3. Call of a pyplot function4. Ask the plot to be

displayed

Page 296: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Structure of a program

Structure d’un programmeA program with plot is most athe structured in the followingfashion :

1. Import the pyplotfunctionality of matplotlib

2. The program part thatmake the calculations

3. Call of a pyplot function4. Ask the plot to be

displayed

Page 297: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Structure of a program

Structure d’un programmeA program with plot is most athe structured in the followingfashion :1. Import the pyplot

functionality of matplotlib

2. The program part thatmake the calculations

3. Call of a pyplot function4. Ask the plot to be

displayed

Page 298: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Structure of a program

Structure d’un programmeA program with plot is most athe structured in the followingfashion :1. Import the pyplot

functionality of matplotlib2. The program part that

make the calculations

3. Call of a pyplot function4. Ask the plot to be

displayed

Page 299: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Structure of a program

Structure d’un programmeA program with plot is most athe structured in the followingfashion :1. Import the pyplot

functionality of matplotlib2. The program part that

make the calculations3. Call of a pyplot function

4. Ask the plot to bedisplayed

Page 300: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Structure of a program

Structure d’un programmeA program with plot is most athe structured in the followingfashion :1. Import the pyplot

functionality of matplotlib2. The program part that

make the calculations3. Call of a pyplot function4. Ask the plot to be

displayed

Page 301: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Outline

1. Introduction

2. 2D plots

3. Multiple plots

4. Titles

5. Legend

6. Axis range

Page 302: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Outline

2. 2D plots2.1 Scatter points2.2 Courbes2.3 Curves+markers

Page 303: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Scatter points

Scatter pointsTo plot Y as a function of X, use the followingsyntax :plt.scatter(X,Y)

Example

Page 304: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Scatter points

Scatter pointsTo plot Y as a function of X, use the followingsyntax :plt.scatter(X,Y)

Example

Page 305: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Scatter points

Scatter pointsTo plot Y as a function of X, use the followingsyntax :plt.scatter(X,Y)

Example

Page 306: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Scatter points

Scatter points : Some optionsChange the marker styleUse the option marker=Change the marker sizeUse the option s= (20 is the default)Change the marker colorUse the option c=

Page 307: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Scatter points

Scatter points : The various markers style

Page 308: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Scatter points

Scatter points : the various marker colorsvalue color’b’ blue’g’ green’r’ red’c’ cyan’m’ magenta’y’ yellow’k’ black’w’ white

Page 309: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Scatter points

Scatter points : Some options : Example

Page 310: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Scatter points

Scatter points : Some options : Example

Page 311: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Scatter points

Scatter points : Some options : Example

Page 312: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Scatter points

Scatter points : CustomizationOn could also define marker colors and sizes for eachpoints using lists :(ATTENTION : the size of these lists should be thesame as the data lists)

Example

Page 313: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Scatter points

Scatter points : CustomizationOn could also define marker colors and sizes for eachpoints using lists :(ATTENTION : the size of these lists should be thesame as the data lists)

Example

Page 314: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Scatter points

Scatter points : CustomizationOn could also define marker colors and sizes for eachpoints using lists :(ATTENTION : the size of these lists should be thesame as the data lists)

Example

Page 315: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Outline

2. 2D plots2.1 Scatter points2.2 Courbes2.3 Curves+markers

Page 316: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves

CurvesTo plot Y as a function of X, use the followingsyntax :plt.plot(X,Y)

Example

Page 317: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves

CurvesTo plot Y as a function of X, use the followingsyntax :plt.plot(X,Y)

Example

Page 318: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves

CurvesTo plot Y as a function of X, use the followingsyntax :plt.plot(X,Y)

Example

Page 319: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves

Curves : Some optionsChange the linestyleUse the option linestyle=Change the linewidthUse the option linewidth=Change the line colorUse the option color=

Page 320: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves

Curves : Some optionsChange the linestyleUse the option linestyle=Change the linewidthUse the option linewidth=Change the line colorUse the option color=

Page 321: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves

Curves : The various line colorsvalue color’b’ blue’g’ green’r’ red’c’ cyan’m’ magenta’y’ yellow’k’ black’w’ white

Page 322: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves

Curves : The various line stylesvalue linestyle’ :’ doted’-.’ doted and dashed’–’ dashed

Page 323: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves

Curves : Some options : Example

Page 324: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves

Curves : Some options : Example

Page 325: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves

Curves : Some options : Example

Page 326: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Outline

2. 2D plots2.1 Scatter points2.2 Courbes2.3 Curves+markers

Page 327: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves+markers

Curves+markersIt is possible to combine both curves and scatterpoints.To do so, use the curves plot method and add themarker= option.

Example

Page 328: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves+markers

Curves+markersIt is possible to combine both curves and scatterpoints.To do so, use the curves plot method and add themarker= option.

Example

Page 329: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves+markers

Curves+markersIt is possible to combine both curves and scatterpoints.To do so, use the curves plot method and add themarker= option.

Example

Page 330: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves+markers

Curves+markers : Some optionsChange the marker colorUse the option markeredgecolor= and markerfacecolorChange marker sizeUse the option markersize=

Page 331: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves+markers

Curves+markers : Some optionsChange the marker colorUse the option markeredgecolor= and markerfacecolorChange marker sizeUse the option markersize=

Page 332: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves+markers

Curves+markers : Some options : Example

Page 333: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves+markers

Curves+markers : Some options : Example

Page 334: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Curves+markers

Curves+markers : Some options : Example

Page 335: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Outline

1. Introduction

2. 2D plots

3. Multiple plots

4. Titles

5. Legend

6. Axis range

Page 336: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Outline

3. Multiple plots3.1 On the same graph3.2 On 2 graphs

Page 337: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Multiples plot

2 plotsIf you want to have 2 curves on the same plot, usetwice the plot function

Example

Page 338: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Multiples plot

2 plotsIf you want to have 2 curves on the same plot, usetwice the plot function

Example

Page 339: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Multiples plot

2 plotsIf you want to have 2 curves on the same plot, usetwice the plot function

Example

Page 340: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Outline

3. Multiple plots3.1 On the same graph3.2 On 2 graphs

Page 341: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Multiple plots

2 plotsIf you want to have 2 curves on 2 different graphs, usethe subplot function

Different type of subplots▶ X common axis▶ Y common axis▶ X and Y common axis▶ No common axis

Page 342: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Multiple plots

2 plotsIf you want to have 2 curves on 2 different graphs, usethe subplot function

Different type of subplots▶ X common axis▶ Y common axis▶ X and Y common axis▶ No common axis

Page 343: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Multiples plots : X common axis

SyntaxUse the subplot function with the syntax :f, ax = plt.subplots(2,sharex=True) where 2 specifythat you want 2 graphs.

Example

Page 344: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Multiples plots : X common axis

SyntaxUse the subplot function with the syntax :f, ax = plt.subplots(2,sharex=True) where 2 specifythat you want 2 graphs.

Example

Page 345: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Multiples plots : X common axis

SyntaxUse the subplot function with the syntax :f, ax = plt.subplots(2,sharex=True) where 2 specifythat you want 2 graphs.

Example

Page 346: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Multiples plots : Y common axis

SyntaxUse the subplot function with the syntax :f, (ax1,ax2) = plt.subplots(1,2,sharex=True) where 1and 2 specify that you want 1 graph vertically and 2horizontally.

Exemple

Page 347: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Multiples plots : Y common axis

SyntaxUse the subplot function with the syntax :f, (ax1,ax2) = plt.subplots(1,2,sharex=True) where 1and 2 specify that you want 1 graph vertically and 2horizontally.

Exemple

Page 348: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Multiples plots : Y common axis

SyntaxUse the subplot function with the syntax :f, (ax1,ax2) = plt.subplots(1,2,sharex=True) where 1and 2 specify that you want 1 graph vertically and 2horizontally.

Exemple

Page 349: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Multiples plots : X and Ycommon axis

SyntaxUse the subplot function with the syntax :f, ax = plt.subplots(2,sharex=True, sharey=True)where 2 specify that you want 2 graphs.

Exemple

Page 350: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Multiples plots : X and Ycommon axis

SyntaxUse the subplot function with the syntax :f, ax = plt.subplots(2,sharex=True, sharey=True)where 2 specify that you want 2 graphs.

Exemple

Page 351: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Multiples plots : X and Ycommon axis

SyntaxUse the subplot function with the syntax :f, ax = plt.subplots(2,sharex=True, sharey=True)where 2 specify that you want 2 graphs.

Exemple

Page 352: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Multiples plots : No commonaxis

SyntaxUse the subplot function with the syntax :f, ax = plt.subplots(2) where 2 specify that you want2 graphs.

Exemple

Page 353: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Multiples plots : No commonaxis

SyntaxUse the subplot function with the syntax :f, ax = plt.subplots(2) where 2 specify that you want2 graphs.

Exemple

Page 354: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Matplotlib : Multiples plots : No commonaxis

SyntaxUse the subplot function with the syntax :f, ax = plt.subplots(2) where 2 specify that you want2 graphs.

Exemple

Page 355: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Outline

1. Introduction

2. 2D plots

3. Multiple plots

4. Titles

5. Legend

6. Axis range

Page 356: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Outline

4. Titles4.1 Graph title4.2 Axis titles

Page 357: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Graph title : single graph

Add a title to a graphTo add a graph title, use the following syntax :plt.title(title_name)

Example

Page 358: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Graph title : single graph

Add a title to a graphTo add a graph title, use the following syntax :plt.title(title_name)

Example

Page 359: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Graph title : single graph

Add a title to a graphTo add a graph title, use the following syntax :plt.title(title_name)

Example

Page 360: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Graph title : Subplots

Add a subplot titleTo a dd a global graph title, use :suptitle(title_name)To add a subplot title, use :set_title(title_name)

Exemple

Page 361: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Graph title : Subplots

Add a subplot titleTo a dd a global graph title, use :suptitle(title_name)To add a subplot title, use :set_title(title_name)

Exemple

Page 362: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Graph title : Subplots

Add a subplot titleTo a dd a global graph title, use :suptitle(title_name)To add a subplot title, use :set_title(title_name)

Exemple

Page 363: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Outline

4. Titles4.1 Graph title4.2 Axis titles

Page 364: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Axis title : Single graph

Add axix titlesTo add axis titles, use :plt.xlabel(X_axis_title) and plt.ylabel(Y_axis_title)

Example

Page 365: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Axis title : Single graph

Add axix titlesTo add axis titles, use :plt.xlabel(X_axis_title) and plt.ylabel(Y_axis_title)

Example

Page 366: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Axis title : Single graph

Add axix titlesTo add axis titles, use :plt.xlabel(X_axis_title) and plt.ylabel(Y_axis_title)

Example

Page 367: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Axis titles : Subplots

Add axis titlesTo add axis titles, use :set_xlabel(X_axis_title) et set_ylabel(Y_axis_title)

Exemple

Page 368: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Axis titles : Subplots

Add axis titlesTo add axis titles, use :set_xlabel(X_axis_title) et set_ylabel(Y_axis_title)

Exemple

Page 369: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Axis titles : Subplots

Add axis titlesTo add axis titles, use :set_xlabel(X_axis_title) et set_ylabel(Y_axis_title)

Exemple

Page 370: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Outline

1. Introduction

2. 2D plots

3. Multiple plots

4. Titles

5. Legend

6. Axis range

Page 371: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Legend : single graphique

Add a legendTo add a legend, use :label= option for each plot and plt.legend to showlegend.

Example

Page 372: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Legend : single graphique

Add a legendTo add a legend, use :label= option for each plot and plt.legend to showlegend.

Example

Page 373: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Legend : single graphique

Add a legendTo add a legend, use :label= option for each plot and plt.legend to showlegend.

Example

Page 374: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

legend : Subplots

Add a legendPTo add a legend to each subplots, use :label= option for each plot and .legend to showlegends.

Exemple

Page 375: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

legend : Subplots

Add a legendPTo add a legend to each subplots, use :label= option for each plot and .legend to showlegends.

Exemple

Page 376: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

legend : Subplots

Add a legendPTo add a legend to each subplots, use :label= option for each plot and .legend to showlegends.

Exemple

Page 377: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Outline

1. Introduction

2. 2D plots

3. Multiple plots

4. Titles

5. Legend

6. Axis range

Page 378: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Axis range : Single graphique

Define X and Y rangeTo define X and Y ranges, use :xlim=(min,max) and ylim=(min,max).

Example

Page 379: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Axis range : Single graphique

Define X and Y rangeTo define X and Y ranges, use :xlim=(min,max) and ylim=(min,max).

Example

Page 380: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Axis range : Single graphique

Define X and Y rangeTo define X and Y ranges, use :xlim=(min,max) and ylim=(min,max).

Example

Page 381: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Axis range : Single graphique

Define X and Y rangeTo define X and Y ranges, use :xlim=(min,max) and ylim=(min,max).

Example

Page 382: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Axis range : Single graphique

Define X and Y rangeTo define X and Y ranges, use :xlim=(min,max) and ylim=(min,max).

Example

Page 383: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Axis range : Subplots

Define X and Y rangePTo define X and Y ranges, use :set_xlim=(min,max) and set_ylim=(min,max) foreach subplots.

Exemple

Page 384: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Axis range : Subplots

Define X and Y rangePTo define X and Y ranges, use :set_xlim=(min,max) and set_ylim=(min,max) foreach subplots.

Exemple

Page 385: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Axis range : Subplots

Define X and Y rangePTo define X and Y ranges, use :set_xlim=(min,max) and set_ylim=(min,max) foreach subplots.

Exemple

Page 386: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Axis range : Subplots

Define X and Y rangePTo define X and Y ranges, use :set_xlim=(min,max) and set_ylim=(min,max) foreach subplots.

Exemple

Page 387: Introduction to programmation using the Python language

The matplolib module

IntroductionDefinitionstructure

2D plotsScatter pointsCourbesCurves+markers

Multiple plotsOn the same graphOn 2 graphs

TitlesGraph titleAxis titles

Legend

Axis range

Axis range : Subplots

Define X and Y rangePTo define X and Y ranges, use :set_xlim=(min,max) and set_ylim=(min,max) foreach subplots.

Exemple

Page 388: Introduction to programmation using the Python language

3D plots with matplotlib

Page 389: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Outline

1. Import modules

2. Curves

3. Scatter points

4. Wireframe plot

5. Surface plot

6. 2D Plots

Page 390: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Import modules

As for 2DAs for 2D graphs, you should import pyplot :import matplotlib.pyplot as plt

Addition module for 3DFor 3D plots, you should also import the mplot3Dfunction of the mpl_toolkits module :from mpl_toolkits.mplot3d import Axes3D

Page 391: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Import modules

As for 2DAs for 2D graphs, you should import pyplot :import matplotlib.pyplot as plt

Addition module for 3DFor 3D plots, you should also import the mplot3Dfunction of the mpl_toolkits module :from mpl_toolkits.mplot3d import Axes3D

Page 392: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Import modules

As for 2DAs for 2D graphs, you should import pyplot :import matplotlib.pyplot as plt

Addition module for 3DFor 3D plots, you should also import the mplot3Dfunction of the mpl_toolkits module :from mpl_toolkits.mplot3d import Axes3D

Page 393: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Specific syntax

Create a figureYou should create a particular interface for the figurespecifying that it will be a 3D figure :fig = plt.figure()ax = fig.gca(projection=’3d’)

Page 394: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Specific syntax

Create a figureYou should create a particular interface for the figurespecifying that it will be a 3D figure :fig = plt.figure()ax = fig.gca(projection=’3d’)

Page 395: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Outline

1. Import modules

2. Curves

3. Scatter points

4. Wireframe plot

5. Surface plot

6. 2D Plots

Page 396: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Curves

plot 3D curvesIt works exactly as for 2D except that you should give3 data lists :plt.plot(X,Y,Z)

Example

Page 397: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Curves

plot 3D curvesIt works exactly as for 2D except that you should give3 data lists :plt.plot(X,Y,Z)

Example

Page 398: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Curves

plot 3D curvesIt works exactly as for 2D except that you should give3 data lists :plt.plot(X,Y,Z)

Example

Page 399: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Outline

1. Import modules

2. Curves

3. Scatter points

4. Wireframe plot

5. Surface plot

6. 2D Plots

Page 400: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Scatter points

3D Scatter pointsIt works exactly as for 2D except that you should give3 data lists :plt.scatter(X,Y,Z)

Example

Page 401: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Scatter points

3D Scatter pointsIt works exactly as for 2D except that you should give3 data lists :plt.scatter(X,Y,Z)

Example

Page 402: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Scatter points

3D Scatter pointsIt works exactly as for 2D except that you should give3 data lists :plt.scatter(X,Y,Z)

Example

Page 403: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Outline

1. Import modules

2. Curves

3. Scatter points

4. Wireframe plot

5. Surface plot

6. 2D Plots

Page 404: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Wireframe

Wireframe plotsTo do this, use :plt.wireframe(X,Y,Z)

Example

Page 405: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Wireframe

Wireframe plotsTo do this, use :plt.wireframe(X,Y,Z)

Example

Page 406: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Wireframe

Wireframe plotsTo do this, use :plt.wireframe(X,Y,Z)

Example

Page 407: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Outline

1. Import modules

2. Curves

3. Scatter points

4. Wireframe plot

5. Surface plot

6. 2D Plots

Page 408: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Surface

Surface plotYou should use the following syntax :plt.surface(X,Y,Z)

Example

Page 409: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Surface

Surface plotYou should use the following syntax :plt.surface(X,Y,Z)

Example

Page 410: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Surface

Surface plotYou should use the following syntax :plt.surface(X,Y,Z)

Example

Page 411: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Surface plot

With a color gradientYou can do it using the cmap=cm.colorwarm option :plt.surface(X,Y,Z, cmap=cm.colorwarm)

Example

Page 412: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Surface plot

With a color gradientYou can do it using the cmap=cm.colorwarm option :plt.surface(X,Y,Z, cmap=cm.colorwarm)

Example

Page 413: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : Surface plot

With a color gradientYou can do it using the cmap=cm.colorwarm option :plt.surface(X,Y,Z, cmap=cm.colorwarm)

Example

Page 414: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Outline

1. Import modules

2. Curves

3. Scatter points

4. Wireframe plot

5. Surface plot

6. 2D Plots

Page 415: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : 2D plots

Plot 2DThis can be done by removing a direction (z forexample) :ax.plot(x, y, zs=0, zdir=’z’)

Exemple

Page 416: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : 2D plots

Plot 2DThis can be done by removing a direction (z forexample) :ax.plot(x, y, zs=0, zdir=’z’)

Exemple

Page 417: Introduction to programmation using the Python language

Matplotlib 3D

Import modules

Courbes

Nuages de points

Wireframe

Surface

2D

Matplotlib3D : 2D plots

Plot 2DThis can be done by removing a direction (z forexample) :ax.plot(x, y, zs=0, zdir=’z’)

Exemple