ISUP-python Cours 1

17
ISUP-python Cours 1 variables, type, structure de contrôle (if et while) et fonctions (chapitres 1 à 4 du poly (on ne fait pas le 5))

Transcript of ISUP-python Cours 1

Page 1: ISUP-python Cours 1

ISUP-pythonCours1

variables,type,structuredecontrôle(ifetwhile)etfonctions(chapitres1à4dupoly(onnefaitpasle5))

Page 2: ISUP-python Cours 1

Cequiavaêtrevuaucours1:• Lestypesdebase

Sequence Containers Indexing

Base Types

Python 3 Cheat Sheet©2012-2015 - Laurent Pointal

License Creative Commons Attribution 4

Latest version on :https://perso.limsi.fr/pointal/python:memento

0783 -192int

9.23 -1.7e-60.0floatTrue Falsebool"One\nTwo"

'I\'m'

str"""X\tY\tZ1\t2\t3"""

×10-6

escaped tab

escaped new line

Multiline string:

Container Types

list [1,5,9] ["x",11,8.9] ["mot"] []

tuple (1,5,9) 11,"y",7.4 ("mot",) ()

dict{1:"one",3:"three",2:"two",3.14:"π"}

{"key":"value"}

set

{}

{1,9,3,0}

◾ ordered sequences, fast index access, repeatable values

set()

◾ key containers, no a priori order, fast key acces, each key is unique

{"key1","key2"}

Non modi�able values (immutables)

Variables assignment

x=1.2+8+sin(y)

y,z,r=9.2,-7.6,0

a…zA…Z_ followed by a…zA…Z_0…9◽ diacritics allowed but should be avoided

◽ language keywords forbidden

◽ lower/UPPER case discrimination

☝ expression with just comas →tuple

dictionary

collection

integer, %oat, boolean, string, bytes

Identi�ers

☺ a toto x7 y_max BigOne☹ 8y and for

x+=3x-=2

increment ⇔ x=x+3

decrement ⇔ x=x-2

Conversions

for lists, tuples, strings, bytes…

int("15") → 15int("3f",16) → 63 can specify integer number base in 2

nd parameter

int(15.56) → 15 truncate decimal part

float("-11.24e8") → -1124000000.0round(15.56,1)→ 15.6 rounding to 1 decimal (0 decimal → integer number)

bool(x) False for null x, empty container x , None or False x ; True for other x str(x)→ "…" representation string of x for display (cf. formating on the back)chr(64)→'@' ord('@')→64 code ↔ char

repr(x)→ "…" literal representation string of xbytes([72,9,64]) → b'H\t@'list("abc") → ['a','b','c']dict([(3,"three"),(1,"one")]) → {1:'one',3:'three'}set(["one","two"]) → {'one','two'}separator str and sequence of str → assembled str

':'.join(['toto','12','pswd']) → 'toto:12:pswd'str splitted on whitespaces → list of str

"words with spaces".split() → ['words','with','spaces']str splitted on separator str → list of str

"1,4,8,2".split(",") → ['1','4','8','2']sequence of one type → list of another type (via comprehension list)

[int(x) for x in ('1','29','-3')] → [1,29,-3]

type(expression)

lst=[10, 20, 30, 40, 50]lst[1]→20lst[-2]→40

0 1 2 3 4-5 -4 -3 -1-2 Individual access to items via lst[index]

positive index

negative index

0 1 2 3 54

-5 -4 -3 -1-2negative slice

positive slice

Access to sub-sequences via lst[start slice:end slice:step]

len(lst)→5

lst[1:3]→[20,30]

lst[::2]→[10,30,50]lst[-3:-1]→[30,40]

lst[:3]→[10,20,30]lst[:-1]→[10,20,30,40]lst[3:]→[40,50]lst[1:-1]→[20,30,40]

lst[:]→[10,20,30,40,50]Missing slice indication → from start / up to end.On mutable sequences (list), remove with del lst[3:5] and modify with assignment lst[1:4]=[15,25]

Conditional Statement

if age<=18: state="Kid"elif age>65: state="Retired"else: state="Active"

Boolean Logic Statements Blocks

parent statement: statement block 1… ⁝ parent statement: statement block2… ⁝

next statement after block 1

ind

enta

tion

 !

Comparators: < > <= >= == !=≠=≥≤

a and b

a or b

not a

logical and

logical or

logical not

one or other or both

both simulta--neously

if logical condition: statements block

statement block executed onlyif a condition is true

Can go with several elif, elif... and only one

8nal else. Only the block of 8rst true

condition is executed.

lst[-1]→50lst[0]→10

⇒ last one

⇒ �rst one

x=None « unde�ned » constant value

Maths

Operators: + - * / // % **× ÷

integer ÷ ÷ remainder

ab

from math import sin,pi…sin(pi/4)→0.707…cos(2*pi/3)→-0.4999…sqrt(81)→9.0 √log(e**2)→2.0ceil(12.5)→13floor(12.5)→12

escaped '

☝ %oating numbers… approximated values angles in radians

(1+5.3)*2→12.6abs(-3.2)→3.2round(3.57,1)→3.6pow(4,3)→64.0

for variables, functions,modules, classes… names

Mémento v2.0.4

str (ordered sequences of chars / bytes)

(key/value associations)

☝ pitfall : and and or return value of a or of b (under shortcut evaluation). ⇒ ensure that a and b are booleans.

(boolean results)

a=b=c=0 assignment to same value

multiple assignments

a,b=b,a values swap

a,*b=seq*a,b=seq

unpacking of sequence initem and list

bytes

bytes

b"toto\xfe\775"

hexadecimal octal

0b010 0xF30o642binary octal hexa

""

empty

dict(a=3,b=4,k="v")

Items count

☝ keys=hashable values (base types, immutables…)

TrueFalse True and False constants ☝ con�gure editor to insert 4 spaces in

place of an indentation tab.

lst[::-1]→[50,40,30,20,10]lst[::-2]→[50,30,10]

1) evaluation of right side expression value2) assignment in order with left side names

=

☝ assignment ⇔ binding of a name with a value

☝ immutables

On mutable sequences (list), remove with del lst[3] and modify with assignment lst[4]=25

del x remove name x

b""

@ → matrix × python3.5+numpy

☝ index from 0(here from 0 to 4)

frozenset immutable set

Priority (…)

☝ usual prioritiesmodules math, statistics, random,

decimal, fractions, numpy, etc. (cf. doc)

Modules/Names Importsfrom monmod import nom1,nom2 as fctmodule truc⇔�le truc.py

→direct acces to names, renaming with asimport monmod →acces via monmod.nom1 …

☝ modules and packages searched in python path (cf sys.path)

?yes

no

shallow copy of sequence

?yes no

and

*=/=%=…

☝ with a var x:if bool(x)==True: ⇔ if x:if bool(x)==False:⇔ if not x:

Exceptions on Errorsraise Exception(…)

Signaling an error:Errors processing:try: normal procesising block except Exception as e: error processing block

normal

processing

errorprocessing

errorprocessing raise

raise

null

☝ finally block for �nal processing in all cases.

Page 3: ISUP-python Cours 1

Cequiavaêtrevuaucours1:• Lestypesdebase

• Affectationdevariables

Sequence Containers Indexing

Base Types

Python 3 Cheat Sheet©2012-2015 - Laurent Pointal

License Creative Commons Attribution 4

Latest version on :https://perso.limsi.fr/pointal/python:memento

0783 -192int

9.23 -1.7e-60.0floatTrue Falsebool"One\nTwo"

'I\'m'

str"""X\tY\tZ1\t2\t3"""

×10-6

escaped tab

escaped new line

Multiline string:

Container Types

list [1,5,9] ["x",11,8.9] ["mot"] []

tuple (1,5,9) 11,"y",7.4 ("mot",) ()

dict{1:"one",3:"three",2:"two",3.14:"π"}

{"key":"value"}

set

{}

{1,9,3,0}

◾ ordered sequences, fast index access, repeatable values

set()

◾ key containers, no a priori order, fast key acces, each key is unique

{"key1","key2"}

Non modi�able values (immutables)

Variables assignment

x=1.2+8+sin(y)

y,z,r=9.2,-7.6,0

a…zA…Z_ followed by a…zA…Z_0…9◽ diacritics allowed but should be avoided

◽ language keywords forbidden

◽ lower/UPPER case discrimination

☝ expression with just comas →tuple

dictionary

collection

integer, %oat, boolean, string, bytes

Identi�ers

☺ a toto x7 y_max BigOne☹ 8y and for

x+=3x-=2

increment ⇔ x=x+3

decrement ⇔ x=x-2

Conversions

for lists, tuples, strings, bytes…

int("15") → 15int("3f",16) → 63 can specify integer number base in 2

nd parameter

int(15.56) → 15 truncate decimal part

float("-11.24e8") → -1124000000.0round(15.56,1)→ 15.6 rounding to 1 decimal (0 decimal → integer number)

bool(x) False for null x, empty container x , None or False x ; True for other x str(x)→ "…" representation string of x for display (cf. formating on the back)chr(64)→'@' ord('@')→64 code ↔ char

repr(x)→ "…" literal representation string of xbytes([72,9,64]) → b'H\t@'list("abc") → ['a','b','c']dict([(3,"three"),(1,"one")]) → {1:'one',3:'three'}set(["one","two"]) → {'one','two'}separator str and sequence of str → assembled str

':'.join(['toto','12','pswd']) → 'toto:12:pswd'str splitted on whitespaces → list of str

"words with spaces".split() → ['words','with','spaces']str splitted on separator str → list of str

"1,4,8,2".split(",") → ['1','4','8','2']sequence of one type → list of another type (via comprehension list)

[int(x) for x in ('1','29','-3')] → [1,29,-3]

type(expression)

lst=[10, 20, 30, 40, 50]lst[1]→20lst[-2]→40

0 1 2 3 4-5 -4 -3 -1-2 Individual access to items via lst[index]

positive index

negative index

0 1 2 3 54

-5 -4 -3 -1-2negative slice

positive slice

Access to sub-sequences via lst[start slice:end slice:step]

len(lst)→5

lst[1:3]→[20,30]

lst[::2]→[10,30,50]lst[-3:-1]→[30,40]

lst[:3]→[10,20,30]lst[:-1]→[10,20,30,40]lst[3:]→[40,50]lst[1:-1]→[20,30,40]

lst[:]→[10,20,30,40,50]Missing slice indication → from start / up to end.On mutable sequences (list), remove with del lst[3:5] and modify with assignment lst[1:4]=[15,25]

Conditional Statement

if age<=18: state="Kid"elif age>65: state="Retired"else: state="Active"

Boolean Logic Statements Blocks

parent statement: statement block 1… ⁝ parent statement: statement block2… ⁝

next statement after block 1

ind

enta

tion

 !

Comparators: < > <= >= == !=≠=≥≤

a and b

a or b

not a

logical and

logical or

logical not

one or other or both

both simulta--neously

if logical condition: statements block

statement block executed onlyif a condition is true

Can go with several elif, elif... and only one

8nal else. Only the block of 8rst true

condition is executed.

lst[-1]→50lst[0]→10

⇒ last one

⇒ �rst one

x=None « unde�ned » constant value

Maths

Operators: + - * / // % **× ÷

integer ÷ ÷ remainder

ab

from math import sin,pi…sin(pi/4)→0.707…cos(2*pi/3)→-0.4999…sqrt(81)→9.0 √log(e**2)→2.0ceil(12.5)→13floor(12.5)→12

escaped '

☝ %oating numbers… approximated values angles in radians

(1+5.3)*2→12.6abs(-3.2)→3.2round(3.57,1)→3.6pow(4,3)→64.0

for variables, functions,modules, classes… names

Mémento v2.0.4

str (ordered sequences of chars / bytes)

(key/value associations)

☝ pitfall : and and or return value of a or of b (under shortcut evaluation). ⇒ ensure that a and b are booleans.

(boolean results)

a=b=c=0 assignment to same value

multiple assignments

a,b=b,a values swap

a,*b=seq*a,b=seq

unpacking of sequence initem and list

bytes

bytes

b"toto\xfe\775"

hexadecimal octal

0b010 0xF30o642binary octal hexa

""

empty

dict(a=3,b=4,k="v")

Items count

☝ keys=hashable values (base types, immutables…)

TrueFalse True and False constants ☝ con�gure editor to insert 4 spaces in

place of an indentation tab.

lst[::-1]→[50,40,30,20,10]lst[::-2]→[50,30,10]

1) evaluation of right side expression value2) assignment in order with left side names

=

☝ assignment ⇔ binding of a name with a value

☝ immutables

On mutable sequences (list), remove with del lst[3] and modify with assignment lst[4]=25

del x remove name x

b""

@ → matrix × python3.5+numpy

☝ index from 0(here from 0 to 4)

frozenset immutable set

Priority (…)

☝ usual prioritiesmodules math, statistics, random,

decimal, fractions, numpy, etc. (cf. doc)

Modules/Names Importsfrom monmod import nom1,nom2 as fctmodule truc⇔�le truc.py

→direct acces to names, renaming with asimport monmod →acces via monmod.nom1 …

☝ modules and packages searched in python path (cf sys.path)

?yes

no

shallow copy of sequence

?yes no

and

*=/=%=…

☝ with a var x:if bool(x)==True: ⇔ if x:if bool(x)==False:⇔ if not x:

Exceptions on Errorsraise Exception(…)

Signaling an error:Errors processing:try: normal procesising block except Exception as e: error processing block

normal

processing

errorprocessing

errorprocessing raise

raise

null

☝ finally block for �nal processing in all cases.

Page 4: ISUP-python Cours 1

Cequiavaêtrevuaucours1:• Lestypesdebase

• Affectationdevariables

• Lesnoms(identifieurs)devariables,fonctions…

Sequence Containers Indexing

Base Types

Python 3 Cheat Sheet©2012-2015 - Laurent Pointal

License Creative Commons Attribution 4

Latest version on :https://perso.limsi.fr/pointal/python:memento

0783 -192int

9.23 -1.7e-60.0floatTrue Falsebool"One\nTwo"

'I\'m'

str"""X\tY\tZ1\t2\t3"""

×10-6

escaped tab

escaped new line

Multiline string:

Container Types

list [1,5,9] ["x",11,8.9] ["mot"] []

tuple (1,5,9) 11,"y",7.4 ("mot",) ()

dict{1:"one",3:"three",2:"two",3.14:"π"}

{"key":"value"}

set

{}

{1,9,3,0}

◾ ordered sequences, fast index access, repeatable values

set()

◾ key containers, no a priori order, fast key acces, each key is unique

{"key1","key2"}

Non modi�able values (immutables)

Variables assignment

x=1.2+8+sin(y)

y,z,r=9.2,-7.6,0

a…zA…Z_ followed by a…zA…Z_0…9◽ diacritics allowed but should be avoided

◽ language keywords forbidden

◽ lower/UPPER case discrimination

☝ expression with just comas →tuple

dictionary

collection

integer, %oat, boolean, string, bytes

Identi�ers

☺ a toto x7 y_max BigOne☹ 8y and for

x+=3x-=2

increment ⇔ x=x+3

decrement ⇔ x=x-2

Conversions

for lists, tuples, strings, bytes…

int("15") → 15int("3f",16) → 63 can specify integer number base in 2

nd parameter

int(15.56) → 15 truncate decimal part

float("-11.24e8") → -1124000000.0round(15.56,1)→ 15.6 rounding to 1 decimal (0 decimal → integer number)

bool(x) False for null x, empty container x , None or False x ; True for other x str(x)→ "…" representation string of x for display (cf. formating on the back)chr(64)→'@' ord('@')→64 code ↔ char

repr(x)→ "…" literal representation string of xbytes([72,9,64]) → b'H\t@'list("abc") → ['a','b','c']dict([(3,"three"),(1,"one")]) → {1:'one',3:'three'}set(["one","two"]) → {'one','two'}separator str and sequence of str → assembled str

':'.join(['toto','12','pswd']) → 'toto:12:pswd'str splitted on whitespaces → list of str

"words with spaces".split() → ['words','with','spaces']str splitted on separator str → list of str

"1,4,8,2".split(",") → ['1','4','8','2']sequence of one type → list of another type (via comprehension list)

[int(x) for x in ('1','29','-3')] → [1,29,-3]

type(expression)

lst=[10, 20, 30, 40, 50]lst[1]→20lst[-2]→40

0 1 2 3 4-5 -4 -3 -1-2 Individual access to items via lst[index]

positive index

negative index

0 1 2 3 54

-5 -4 -3 -1-2negative slice

positive slice

Access to sub-sequences via lst[start slice:end slice:step]

len(lst)→5

lst[1:3]→[20,30]

lst[::2]→[10,30,50]lst[-3:-1]→[30,40]

lst[:3]→[10,20,30]lst[:-1]→[10,20,30,40]lst[3:]→[40,50]lst[1:-1]→[20,30,40]

lst[:]→[10,20,30,40,50]Missing slice indication → from start / up to end.On mutable sequences (list), remove with del lst[3:5] and modify with assignment lst[1:4]=[15,25]

Conditional Statement

if age<=18: state="Kid"elif age>65: state="Retired"else: state="Active"

Boolean Logic Statements Blocks

parent statement: statement block 1… ⁝ parent statement: statement block2… ⁝

next statement after block 1

ind

enta

tion

 !

Comparators: < > <= >= == !=≠=≥≤

a and b

a or b

not a

logical and

logical or

logical not

one or other or both

both simulta--neously

if logical condition: statements block

statement block executed onlyif a condition is true

Can go with several elif, elif... and only one

8nal else. Only the block of 8rst true

condition is executed.

lst[-1]→50lst[0]→10

⇒ last one

⇒ �rst one

x=None « unde�ned » constant value

Maths

Operators: + - * / // % **× ÷

integer ÷ ÷ remainder

ab

from math import sin,pi…sin(pi/4)→0.707…cos(2*pi/3)→-0.4999…sqrt(81)→9.0 √log(e**2)→2.0ceil(12.5)→13floor(12.5)→12

escaped '

☝ %oating numbers… approximated values angles in radians

(1+5.3)*2→12.6abs(-3.2)→3.2round(3.57,1)→3.6pow(4,3)→64.0

for variables, functions,modules, classes… names

Mémento v2.0.4

str (ordered sequences of chars / bytes)

(key/value associations)

☝ pitfall : and and or return value of a or of b (under shortcut evaluation). ⇒ ensure that a and b are booleans.

(boolean results)

a=b=c=0 assignment to same value

multiple assignments

a,b=b,a values swap

a,*b=seq*a,b=seq

unpacking of sequence initem and list

bytes

bytes

b"toto\xfe\775"

hexadecimal octal

0b010 0xF30o642binary octal hexa

""

empty

dict(a=3,b=4,k="v")

Items count

☝ keys=hashable values (base types, immutables…)

TrueFalse True and False constants ☝ con�gure editor to insert 4 spaces in

place of an indentation tab.

lst[::-1]→[50,40,30,20,10]lst[::-2]→[50,30,10]

1) evaluation of right side expression value2) assignment in order with left side names

=

☝ assignment ⇔ binding of a name with a value

☝ immutables

On mutable sequences (list), remove with del lst[3] and modify with assignment lst[4]=25

del x remove name x

b""

@ → matrix × python3.5+numpy

☝ index from 0(here from 0 to 4)

frozenset immutable set

Priority (…)

☝ usual prioritiesmodules math, statistics, random,

decimal, fractions, numpy, etc. (cf. doc)

Modules/Names Importsfrom monmod import nom1,nom2 as fctmodule truc⇔�le truc.py

→direct acces to names, renaming with asimport monmod →acces via monmod.nom1 …

☝ modules and packages searched in python path (cf sys.path)

?yes

no

shallow copy of sequence

?yes no

and

*=/=%=…

☝ with a var x:if bool(x)==True: ⇔ if x:if bool(x)==False:⇔ if not x:

Exceptions on Errorsraise Exception(…)

Signaling an error:Errors processing:try: normal procesising block except Exception as e: error processing block

normal

processing

errorprocessing

errorprocessing raise

raise

null

☝ finally block for �nal processing in all cases.

Page 5: ISUP-python Cours 1

Cequiavaêtrevuaucours1:• Lestypesdebase

• Lesnoms(identifieurs)devariables,fonctions…

• Affectationdevariables

• Quelquesconversions:stringverstypedebase

Sequence Containers Indexing

Base Types

Python 3 Cheat Sheet©2012-2015 - Laurent Pointal

License Creative Commons Attribution 4

Latest version on :https://perso.limsi.fr/pointal/python:memento

0783 -192int

9.23 -1.7e-60.0floatTrue Falsebool"One\nTwo"

'I\'m'

str"""X\tY\tZ1\t2\t3"""

×10-6

escaped tab

escaped new line

Multiline string:

Container Types

list [1,5,9] ["x",11,8.9] ["mot"] []

tuple (1,5,9) 11,"y",7.4 ("mot",) ()

dict{1:"one",3:"three",2:"two",3.14:"π"}

{"key":"value"}

set

{}

{1,9,3,0}

◾ ordered sequences, fast index access, repeatable values

set()

◾ key containers, no a priori order, fast key acces, each key is unique

{"key1","key2"}

Non modi�able values (immutables)

Variables assignment

x=1.2+8+sin(y)

y,z,r=9.2,-7.6,0

a…zA…Z_ followed by a…zA…Z_0…9◽ diacritics allowed but should be avoided

◽ language keywords forbidden

◽ lower/UPPER case discrimination

☝ expression with just comas →tuple

dictionary

collection

integer, %oat, boolean, string, bytes

Identi�ers

☺ a toto x7 y_max BigOne☹ 8y and for

x+=3x-=2

increment ⇔ x=x+3

decrement ⇔ x=x-2

Conversions

for lists, tuples, strings, bytes…

int("15") → 15int("3f",16) → 63 can specify integer number base in 2

nd parameter

int(15.56) → 15 truncate decimal part

float("-11.24e8") → -1124000000.0round(15.56,1)→ 15.6 rounding to 1 decimal (0 decimal → integer number)

bool(x) False for null x, empty container x , None or False x ; True for other x str(x)→ "…" representation string of x for display (cf. formating on the back)chr(64)→'@' ord('@')→64 code ↔ char

repr(x)→ "…" literal representation string of xbytes([72,9,64]) → b'H\t@'list("abc") → ['a','b','c']dict([(3,"three"),(1,"one")]) → {1:'one',3:'three'}set(["one","two"]) → {'one','two'}separator str and sequence of str → assembled str

':'.join(['toto','12','pswd']) → 'toto:12:pswd'str splitted on whitespaces → list of str

"words with spaces".split() → ['words','with','spaces']str splitted on separator str → list of str

"1,4,8,2".split(",") → ['1','4','8','2']sequence of one type → list of another type (via comprehension list)

[int(x) for x in ('1','29','-3')] → [1,29,-3]

type(expression)

lst=[10, 20, 30, 40, 50]lst[1]→20lst[-2]→40

0 1 2 3 4-5 -4 -3 -1-2 Individual access to items via lst[index]

positive index

negative index

0 1 2 3 54

-5 -4 -3 -1-2negative slice

positive slice

Access to sub-sequences via lst[start slice:end slice:step]

len(lst)→5

lst[1:3]→[20,30]

lst[::2]→[10,30,50]lst[-3:-1]→[30,40]

lst[:3]→[10,20,30]lst[:-1]→[10,20,30,40]lst[3:]→[40,50]lst[1:-1]→[20,30,40]

lst[:]→[10,20,30,40,50]Missing slice indication → from start / up to end.On mutable sequences (list), remove with del lst[3:5] and modify with assignment lst[1:4]=[15,25]

Conditional Statement

if age<=18: state="Kid"elif age>65: state="Retired"else: state="Active"

Boolean Logic Statements Blocks

parent statement: statement block 1… ⁝ parent statement: statement block2… ⁝

next statement after block 1

ind

enta

tion

 !

Comparators: < > <= >= == !=≠=≥≤

a and b

a or b

not a

logical and

logical or

logical not

one or other or both

both simulta--neously

if logical condition: statements block

statement block executed onlyif a condition is true

Can go with several elif, elif... and only one

8nal else. Only the block of 8rst true

condition is executed.

lst[-1]→50lst[0]→10

⇒ last one

⇒ �rst one

x=None « unde�ned » constant value

Maths

Operators: + - * / // % **× ÷

integer ÷ ÷ remainder

ab

from math import sin,pi…sin(pi/4)→0.707…cos(2*pi/3)→-0.4999…sqrt(81)→9.0 √log(e**2)→2.0ceil(12.5)→13floor(12.5)→12

escaped '

☝ %oating numbers… approximated values angles in radians

(1+5.3)*2→12.6abs(-3.2)→3.2round(3.57,1)→3.6pow(4,3)→64.0

for variables, functions,modules, classes… names

Mémento v2.0.4

str (ordered sequences of chars / bytes)

(key/value associations)

☝ pitfall : and and or return value of a or of b (under shortcut evaluation). ⇒ ensure that a and b are booleans.

(boolean results)

a=b=c=0 assignment to same value

multiple assignments

a,b=b,a values swap

a,*b=seq*a,b=seq

unpacking of sequence initem and list

bytes

bytes

b"toto\xfe\775"

hexadecimal octal

0b010 0xF30o642binary octal hexa

""

empty

dict(a=3,b=4,k="v")

Items count

☝ keys=hashable values (base types, immutables…)

TrueFalse True and False constants ☝ con�gure editor to insert 4 spaces in

place of an indentation tab.

lst[::-1]→[50,40,30,20,10]lst[::-2]→[50,30,10]

1) evaluation of right side expression value2) assignment in order with left side names

=

☝ assignment ⇔ binding of a name with a value

☝ immutables

On mutable sequences (list), remove with del lst[3] and modify with assignment lst[4]=25

del x remove name x

b""

@ → matrix × python3.5+numpy

☝ index from 0(here from 0 to 4)

frozenset immutable set

Priority (…)

☝ usual prioritiesmodules math, statistics, random,

decimal, fractions, numpy, etc. (cf. doc)

Modules/Names Importsfrom monmod import nom1,nom2 as fctmodule truc⇔�le truc.py

→direct acces to names, renaming with asimport monmod →acces via monmod.nom1 …

☝ modules and packages searched in python path (cf sys.path)

?yes

no

shallow copy of sequence

?yes no

and

*=/=%=…

☝ with a var x:if bool(x)==True: ⇔ if x:if bool(x)==False:⇔ if not x:

Exceptions on Errorsraise Exception(…)

Signaling an error:Errors processing:try: normal procesising block except Exception as e: error processing block

normal

processing

errorprocessing

errorprocessing raise

raise

null

☝ finally block for �nal processing in all cases.

Page 6: ISUP-python Cours 1

Cequiavaêtrevuaucours1:• Lestypesdebase

• Lesnoms(identifieurs)devariables,fonctions…

• Affectationdevariables

• Quelquesconversions:stringverstypedebase

• Opérateurs

Sequence Containers Indexing

Base Types

Python 3 Cheat Sheet©2012-2015 - Laurent Pointal

License Creative Commons Attribution 4

Latest version on :https://perso.limsi.fr/pointal/python:memento

0783 -192int

9.23 -1.7e-60.0floatTrue Falsebool"One\nTwo"

'I\'m'

str"""X\tY\tZ1\t2\t3"""

×10-6

escaped tab

escaped new line

Multiline string:

Container Types

list [1,5,9] ["x",11,8.9] ["mot"] []

tuple (1,5,9) 11,"y",7.4 ("mot",) ()

dict{1:"one",3:"three",2:"two",3.14:"π"}

{"key":"value"}

set

{}

{1,9,3,0}

◾ ordered sequences, fast index access, repeatable values

set()

◾ key containers, no a priori order, fast key acces, each key is unique

{"key1","key2"}

Non modi�able values (immutables)

Variables assignment

x=1.2+8+sin(y)

y,z,r=9.2,-7.6,0

a…zA…Z_ followed by a…zA…Z_0…9◽ diacritics allowed but should be avoided

◽ language keywords forbidden

◽ lower/UPPER case discrimination

☝ expression with just comas →tuple

dictionary

collection

integer, %oat, boolean, string, bytes

Identi�ers

☺ a toto x7 y_max BigOne☹ 8y and for

x+=3x-=2

increment ⇔ x=x+3

decrement ⇔ x=x-2

Conversions

for lists, tuples, strings, bytes…

int("15") → 15int("3f",16) → 63 can specify integer number base in 2

nd parameter

int(15.56) → 15 truncate decimal part

float("-11.24e8") → -1124000000.0round(15.56,1)→ 15.6 rounding to 1 decimal (0 decimal → integer number)

bool(x) False for null x, empty container x , None or False x ; True for other x str(x)→ "…" representation string of x for display (cf. formating on the back)chr(64)→'@' ord('@')→64 code ↔ char

repr(x)→ "…" literal representation string of xbytes([72,9,64]) → b'H\t@'list("abc") → ['a','b','c']dict([(3,"three"),(1,"one")]) → {1:'one',3:'three'}set(["one","two"]) → {'one','two'}separator str and sequence of str → assembled str

':'.join(['toto','12','pswd']) → 'toto:12:pswd'str splitted on whitespaces → list of str

"words with spaces".split() → ['words','with','spaces']str splitted on separator str → list of str

"1,4,8,2".split(",") → ['1','4','8','2']sequence of one type → list of another type (via comprehension list)

[int(x) for x in ('1','29','-3')] → [1,29,-3]

type(expression)

lst=[10, 20, 30, 40, 50]lst[1]→20lst[-2]→40

0 1 2 3 4-5 -4 -3 -1-2 Individual access to items via lst[index]

positive index

negative index

0 1 2 3 54

-5 -4 -3 -1-2negative slice

positive slice

Access to sub-sequences via lst[start slice:end slice:step]

len(lst)→5

lst[1:3]→[20,30]

lst[::2]→[10,30,50]lst[-3:-1]→[30,40]

lst[:3]→[10,20,30]lst[:-1]→[10,20,30,40]lst[3:]→[40,50]lst[1:-1]→[20,30,40]

lst[:]→[10,20,30,40,50]Missing slice indication → from start / up to end.On mutable sequences (list), remove with del lst[3:5] and modify with assignment lst[1:4]=[15,25]

Conditional Statement

if age<=18: state="Kid"elif age>65: state="Retired"else: state="Active"

Boolean Logic Statements Blocks

parent statement: statement block 1… ⁝ parent statement: statement block2… ⁝

next statement after block 1

ind

enta

tion

 !

Comparators: < > <= >= == !=≠=≥≤

a and b

a or b

not a

logical and

logical or

logical not

one or other or both

both simulta--neously

if logical condition: statements block

statement block executed onlyif a condition is true

Can go with several elif, elif... and only one

8nal else. Only the block of 8rst true

condition is executed.

lst[-1]→50lst[0]→10

⇒ last one

⇒ �rst one

x=None « unde�ned » constant value

Maths

Operators: + - * / // % **× ÷

integer ÷ ÷ remainder

ab

from math import sin,pi…sin(pi/4)→0.707…cos(2*pi/3)→-0.4999…sqrt(81)→9.0 √log(e**2)→2.0ceil(12.5)→13floor(12.5)→12

escaped '

☝ %oating numbers… approximated values angles in radians

(1+5.3)*2→12.6abs(-3.2)→3.2round(3.57,1)→3.6pow(4,3)→64.0

for variables, functions,modules, classes… names

Mémento v2.0.4

str (ordered sequences of chars / bytes)

(key/value associations)

☝ pitfall : and and or return value of a or of b (under shortcut evaluation). ⇒ ensure that a and b are booleans.

(boolean results)

a=b=c=0 assignment to same value

multiple assignments

a,b=b,a values swap

a,*b=seq*a,b=seq

unpacking of sequence initem and list

bytes

bytes

b"toto\xfe\775"

hexadecimal octal

0b010 0xF30o642binary octal hexa

""

empty

dict(a=3,b=4,k="v")

Items count

☝ keys=hashable values (base types, immutables…)

TrueFalse True and False constants ☝ con�gure editor to insert 4 spaces in

place of an indentation tab.

lst[::-1]→[50,40,30,20,10]lst[::-2]→[50,30,10]

1) evaluation of right side expression value2) assignment in order with left side names

=

☝ assignment ⇔ binding of a name with a value

☝ immutables

On mutable sequences (list), remove with del lst[3] and modify with assignment lst[4]=25

del x remove name x

b""

@ → matrix × python3.5+numpy

☝ index from 0(here from 0 to 4)

frozenset immutable set

Priority (…)

☝ usual prioritiesmodules math, statistics, random,

decimal, fractions, numpy, etc. (cf. doc)

Modules/Names Importsfrom monmod import nom1,nom2 as fctmodule truc⇔�le truc.py

→direct acces to names, renaming with asimport monmod →acces via monmod.nom1 …

☝ modules and packages searched in python path (cf sys.path)

?yes

no

shallow copy of sequence

?yes no

and

*=/=%=…

☝ with a var x:if bool(x)==True: ⇔ if x:if bool(x)==False:⇔ if not x:

Exceptions on Errorsraise Exception(…)

Signaling an error:Errors processing:try: normal procesising block except Exception as e: error processing block

normal

processing

errorprocessing

errorprocessing raise

raise

null

☝ finally block for �nal processing in all cases.

Page 7: ISUP-python Cours 1

Cequiavaêtrevuaucours1:• Lestypesdebase

• Lesnoms(identifieurs)devariables,fonctions…

• Affectationdevariables

• Quelquesconversions:stringverstypedebase

• Opérateurs

• OpérationsBooléennes

Sequence Containers Indexing

Base Types

Python 3 Cheat Sheet©2012-2015 - Laurent Pointal

License Creative Commons Attribution 4

Latest version on :https://perso.limsi.fr/pointal/python:memento

0783 -192int

9.23 -1.7e-60.0floatTrue Falsebool"One\nTwo"

'I\'m'

str"""X\tY\tZ1\t2\t3"""

×10-6

escaped tab

escaped new line

Multiline string:

Container Types

list [1,5,9] ["x",11,8.9] ["mot"] []

tuple (1,5,9) 11,"y",7.4 ("mot",) ()

dict{1:"one",3:"three",2:"two",3.14:"π"}

{"key":"value"}

set

{}

{1,9,3,0}

◾ ordered sequences, fast index access, repeatable values

set()

◾ key containers, no a priori order, fast key acces, each key is unique

{"key1","key2"}

Non modi�able values (immutables)

Variables assignment

x=1.2+8+sin(y)

y,z,r=9.2,-7.6,0

a…zA…Z_ followed by a…zA…Z_0…9◽ diacritics allowed but should be avoided

◽ language keywords forbidden

◽ lower/UPPER case discrimination

☝ expression with just comas →tuple

dictionary

collection

integer, %oat, boolean, string, bytes

Identi�ers

☺ a toto x7 y_max BigOne☹ 8y and for

x+=3x-=2

increment ⇔ x=x+3

decrement ⇔ x=x-2

Conversions

for lists, tuples, strings, bytes…

int("15") → 15int("3f",16) → 63 can specify integer number base in 2

nd parameter

int(15.56) → 15 truncate decimal part

float("-11.24e8") → -1124000000.0round(15.56,1)→ 15.6 rounding to 1 decimal (0 decimal → integer number)

bool(x) False for null x, empty container x , None or False x ; True for other x str(x)→ "…" representation string of x for display (cf. formating on the back)chr(64)→'@' ord('@')→64 code ↔ char

repr(x)→ "…" literal representation string of xbytes([72,9,64]) → b'H\t@'list("abc") → ['a','b','c']dict([(3,"three"),(1,"one")]) → {1:'one',3:'three'}set(["one","two"]) → {'one','two'}separator str and sequence of str → assembled str

':'.join(['toto','12','pswd']) → 'toto:12:pswd'str splitted on whitespaces → list of str

"words with spaces".split() → ['words','with','spaces']str splitted on separator str → list of str

"1,4,8,2".split(",") → ['1','4','8','2']sequence of one type → list of another type (via comprehension list)

[int(x) for x in ('1','29','-3')] → [1,29,-3]

type(expression)

lst=[10, 20, 30, 40, 50]lst[1]→20lst[-2]→40

0 1 2 3 4-5 -4 -3 -1-2 Individual access to items via lst[index]

positive index

negative index

0 1 2 3 54

-5 -4 -3 -1-2negative slice

positive slice

Access to sub-sequences via lst[start slice:end slice:step]

len(lst)→5

lst[1:3]→[20,30]

lst[::2]→[10,30,50]lst[-3:-1]→[30,40]

lst[:3]→[10,20,30]lst[:-1]→[10,20,30,40]lst[3:]→[40,50]lst[1:-1]→[20,30,40]

lst[:]→[10,20,30,40,50]Missing slice indication → from start / up to end.On mutable sequences (list), remove with del lst[3:5] and modify with assignment lst[1:4]=[15,25]

Conditional Statement

if age<=18: state="Kid"elif age>65: state="Retired"else: state="Active"

Boolean Logic Statements Blocks

parent statement: statement block 1… ⁝ parent statement: statement block2… ⁝

next statement after block 1

ind

enta

tion

 !

Comparators: < > <= >= == !=≠=≥≤

a and b

a or b

not a

logical and

logical or

logical not

one or other or both

both simulta--neously

if logical condition: statements block

statement block executed onlyif a condition is true

Can go with several elif, elif... and only one

8nal else. Only the block of 8rst true

condition is executed.

lst[-1]→50lst[0]→10

⇒ last one

⇒ �rst one

x=None « unde�ned » constant value

Maths

Operators: + - * / // % **× ÷

integer ÷ ÷ remainder

ab

from math import sin,pi…sin(pi/4)→0.707…cos(2*pi/3)→-0.4999…sqrt(81)→9.0 √log(e**2)→2.0ceil(12.5)→13floor(12.5)→12

escaped '

☝ %oating numbers… approximated values angles in radians

(1+5.3)*2→12.6abs(-3.2)→3.2round(3.57,1)→3.6pow(4,3)→64.0

for variables, functions,modules, classes… names

Mémento v2.0.4

str (ordered sequences of chars / bytes)

(key/value associations)

☝ pitfall : and and or return value of a or of b (under shortcut evaluation). ⇒ ensure that a and b are booleans.

(boolean results)

a=b=c=0 assignment to same value

multiple assignments

a,b=b,a values swap

a,*b=seq*a,b=seq

unpacking of sequence initem and list

bytes

bytes

b"toto\xfe\775"

hexadecimal octal

0b010 0xF30o642binary octal hexa

""

empty

dict(a=3,b=4,k="v")

Items count

☝ keys=hashable values (base types, immutables…)

TrueFalse True and False constants ☝ con�gure editor to insert 4 spaces in

place of an indentation tab.

lst[::-1]→[50,40,30,20,10]lst[::-2]→[50,30,10]

1) evaluation of right side expression value2) assignment in order with left side names

=

☝ assignment ⇔ binding of a name with a value

☝ immutables

On mutable sequences (list), remove with del lst[3] and modify with assignment lst[4]=25

del x remove name x

b""

@ → matrix × python3.5+numpy

☝ index from 0(here from 0 to 4)

frozenset immutable set

Priority (…)

☝ usual prioritiesmodules math, statistics, random,

decimal, fractions, numpy, etc. (cf. doc)

Modules/Names Importsfrom monmod import nom1,nom2 as fctmodule truc⇔�le truc.py

→direct acces to names, renaming with asimport monmod →acces via monmod.nom1 …

☝ modules and packages searched in python path (cf sys.path)

?yes

no

shallow copy of sequence

?yes no

and

*=/=%=…

☝ with a var x:if bool(x)==True: ⇔ if x:if bool(x)==False:⇔ if not x:

Exceptions on Errorsraise Exception(…)

Signaling an error:Errors processing:try: normal procesising block except Exception as e: error processing block

normal

processing

errorprocessing

errorprocessing raise

raise

null

☝ finally block for �nal processing in all cases.

Page 8: ISUP-python Cours 1

Cequiavaêtrevuaucours1:• Lestypesdebase

• Lesnoms(identifieurs)devariables,fonctions…

• Affectationdevariables

• Quelquesconversions:stringverstypedebase

• Opérateurs

• OpérationsBooléennes

• Blocsetif/elseSequence Containers Indexing

Base Types

Python 3 Cheat Sheet©2012-2015 - Laurent Pointal

License Creative Commons Attribution 4

Latest version on :https://perso.limsi.fr/pointal/python:memento

0783 -192int

9.23 -1.7e-60.0floatTrue Falsebool"One\nTwo"

'I\'m'

str"""X\tY\tZ1\t2\t3"""

×10-6

escaped tab

escaped new line

Multiline string:

Container Types

list [1,5,9] ["x",11,8.9] ["mot"] []

tuple (1,5,9) 11,"y",7.4 ("mot",) ()

dict{1:"one",3:"three",2:"two",3.14:"π"}

{"key":"value"}

set

{}

{1,9,3,0}

◾ ordered sequences, fast index access, repeatable values

set()

◾ key containers, no a priori order, fast key acces, each key is unique

{"key1","key2"}

Non modi�able values (immutables)

Variables assignment

x=1.2+8+sin(y)

y,z,r=9.2,-7.6,0

a…zA…Z_ followed by a…zA…Z_0…9◽ diacritics allowed but should be avoided

◽ language keywords forbidden

◽ lower/UPPER case discrimination

☝ expression with just comas →tuple

dictionary

collection

integer, %oat, boolean, string, bytes

Identi�ers

☺ a toto x7 y_max BigOne☹ 8y and for

x+=3x-=2

increment ⇔ x=x+3

decrement ⇔ x=x-2

Conversions

for lists, tuples, strings, bytes…

int("15") → 15int("3f",16) → 63 can specify integer number base in 2

nd parameter

int(15.56) → 15 truncate decimal part

float("-11.24e8") → -1124000000.0round(15.56,1)→ 15.6 rounding to 1 decimal (0 decimal → integer number)

bool(x) False for null x, empty container x , None or False x ; True for other x str(x)→ "…" representation string of x for display (cf. formating on the back)chr(64)→'@' ord('@')→64 code ↔ char

repr(x)→ "…" literal representation string of xbytes([72,9,64]) → b'H\t@'list("abc") → ['a','b','c']dict([(3,"three"),(1,"one")]) → {1:'one',3:'three'}set(["one","two"]) → {'one','two'}separator str and sequence of str → assembled str

':'.join(['toto','12','pswd']) → 'toto:12:pswd'str splitted on whitespaces → list of str

"words with spaces".split() → ['words','with','spaces']str splitted on separator str → list of str

"1,4,8,2".split(",") → ['1','4','8','2']sequence of one type → list of another type (via comprehension list)

[int(x) for x in ('1','29','-3')] → [1,29,-3]

type(expression)

lst=[10, 20, 30, 40, 50]lst[1]→20lst[-2]→40

0 1 2 3 4-5 -4 -3 -1-2 Individual access to items via lst[index]

positive index

negative index

0 1 2 3 54

-5 -4 -3 -1-2negative slice

positive slice

Access to sub-sequences via lst[start slice:end slice:step]

len(lst)→5

lst[1:3]→[20,30]

lst[::2]→[10,30,50]lst[-3:-1]→[30,40]

lst[:3]→[10,20,30]lst[:-1]→[10,20,30,40]lst[3:]→[40,50]lst[1:-1]→[20,30,40]

lst[:]→[10,20,30,40,50]Missing slice indication → from start / up to end.On mutable sequences (list), remove with del lst[3:5] and modify with assignment lst[1:4]=[15,25]

Conditional Statement

if age<=18: state="Kid"elif age>65: state="Retired"else: state="Active"

Boolean Logic Statements Blocks

parent statement: statement block 1… ⁝ parent statement: statement block2… ⁝

next statement after block 1

ind

enta

tion

 !

Comparators: < > <= >= == !=≠=≥≤

a and b

a or b

not a

logical and

logical or

logical not

one or other or both

both simulta--neously

if logical condition: statements block

statement block executed onlyif a condition is true

Can go with several elif, elif... and only one

8nal else. Only the block of 8rst true

condition is executed.

lst[-1]→50lst[0]→10

⇒ last one

⇒ �rst one

x=None « unde�ned » constant value

Maths

Operators: + - * / // % **× ÷

integer ÷ ÷ remainder

ab

from math import sin,pi…sin(pi/4)→0.707…cos(2*pi/3)→-0.4999…sqrt(81)→9.0 √log(e**2)→2.0ceil(12.5)→13floor(12.5)→12

escaped '

☝ %oating numbers… approximated values angles in radians

(1+5.3)*2→12.6abs(-3.2)→3.2round(3.57,1)→3.6pow(4,3)→64.0

for variables, functions,modules, classes… names

Mémento v2.0.4

str (ordered sequences of chars / bytes)

(key/value associations)

☝ pitfall : and and or return value of a or of b (under shortcut evaluation). ⇒ ensure that a and b are booleans.

(boolean results)

a=b=c=0 assignment to same value

multiple assignments

a,b=b,a values swap

a,*b=seq*a,b=seq

unpacking of sequence initem and list

bytes

bytes

b"toto\xfe\775"

hexadecimal octal

0b010 0xF30o642binary octal hexa

""

empty

dict(a=3,b=4,k="v")

Items count

☝ keys=hashable values (base types, immutables…)

TrueFalse True and False constants ☝ con�gure editor to insert 4 spaces in

place of an indentation tab.

lst[::-1]→[50,40,30,20,10]lst[::-2]→[50,30,10]

1) evaluation of right side expression value2) assignment in order with left side names

=

☝ assignment ⇔ binding of a name with a value

☝ immutables

On mutable sequences (list), remove with del lst[3] and modify with assignment lst[4]=25

del x remove name x

b""

@ → matrix × python3.5+numpy

☝ index from 0(here from 0 to 4)

frozenset immutable set

Priority (…)

☝ usual prioritiesmodules math, statistics, random,

decimal, fractions, numpy, etc. (cf. doc)

Modules/Names Importsfrom monmod import nom1,nom2 as fctmodule truc⇔�le truc.py

→direct acces to names, renaming with asimport monmod →acces via monmod.nom1 …

☝ modules and packages searched in python path (cf sys.path)

?yes

no

shallow copy of sequence

?yes no

and

*=/=%=…

☝ with a var x:if bool(x)==True: ⇔ if x:if bool(x)==False:⇔ if not x:

Exceptions on Errorsraise Exception(…)

Signaling an error:Errors processing:try: normal procesising block except Exception as e: error processing block

normal

processing

errorprocessing

errorprocessing raise

raise

null

☝ finally block for �nal processing in all cases.

Page 9: ISUP-python Cours 1

"modele{} {} {}".format(x,y,r)

"{selection:formating!conversion}"

◽ Selection : 2 nom 0.nom 4[key] 0[2]

str

Displayprint("v=",3,"cm :",x,",",y+4)

print options: ◽ sep=" " items separator, default space◽ end="\n" end of print, default new line◽ file=sys.stdout print to 8le, default standard output

items to display : literal values, variables, expressions

loop on dict/set ⇔ loop on keys sequencesuse slices to loop on a subset of a sequence

Conditional Loop Statementstatements block executed as long ascondition is true

while logical condition: statements block

s = 0i = 1

while i <= 100: s = s + i**2 i = i + 1print("sum:",s)

initializations before the loop

condition with a least one variable value (here i)

s= ∑i=1

i=100

i2

☝ make condition variable change !

Iterative Loop Statementstatements block executed for each item of a container or iterator

for var in sequence: statements block

s = "Some text"cnt = 0

for c in s: if c == "e": cnt = cnt + 1print("found",cnt,"'e'")

Go over sequence's values

Algo: count number of e in the string.

Go over sequence's index◽ modify item at index◽ access items around index (before / after)lst = [11,18,9,12,23,4,17]lost = []for idx in range(len(lst)): val = lst[idx] if val > 15: lost.append(val) lst[idx] = 15print("modif:",lst,"-lost:",lost)

Algo: limit values greaterthan 15, memorizingof lost values.

☝ be

ware

of

in�

nite

loo

ps!

initializations before the loop

loop variable, assignment managed by for statement

Operations on Strings

values to formatformating directives

Integers Sequences

Files

s = input("Instructions:")☝ input always returns a string, convert it to required type

(cf. boxed Conversions on the other side).

range(5)→ 0 1 2 3 4 range(2,12,3)→ 2 5 8 11range(3,8)→ 3 4 5 6 7 range(20,5,-5)→ 20 15 10range(len(seq))→ sequence of index of values in seq ☝ range provides an immutable sequence of int constructed as needed

range([start,] end [,step])

f = open("file.txt","w",encoding="utf8")storing data on disk, and reading it back

opening mode◽ 'r' read◽ 'w' write◽ 'a' append◽ …'+' 'x' 'b' 't'

encoding ofchars for text�les: utf8 ascii latin1 …

name of 8leon disk(+path…)

8le variable for operations

f.write("coucou")f.writelines(list of lines)

writing readingf.read([n]) → next chars

if n not speci�ed, read up to end !f.readlines([n]) → list of next linesf.readline() → next line

with open(…) as f: for line in f : # processing ofline

cf. modules os, os.path and pathlib

f.close() ☝ dont forget to close the le after use !

Very common: opening with a guarded block (automatic closing) and reading loop on lines of a text 8le:

Function De�nition

def fct(x,y,z): """documentation""" # statements block, res computation, etc. return res

function name (identi8er)

result value of the call, if no computedresult to return: return None

☝ parameters and allvariables of this block exist only in the block and during the functioncall (think of a “black box”)

named parameters

Function Callr = fct(3,i+2,2*i)

Generic Operations on Containers

read empty string if end of �le

len(c)→ items countmin(c) max(c) sum(c)sorted(c)→ list sorted copyval in c → boolean, membership operator in (absence not in)enumerate(c)→ iterator on (index, value)zip(c1,c2…)→ iterator on tuples containing c

i items at same index

all(c)→ True if all c items evaluated to true, else Falseany(c)→ True if at least one item of c evaluated true, else False

☝ modify original list

lst.append(val) add item at endlst.extend(seq) add sequence of items at endlst.insert(idx,val) insert item at indexlst.remove(val) remove 8rst item with value vallst.pop([idx])→value remove & return item at index idx (default last)

lst.sort() lst.reverse() sort / reverse liste in place

"{:+2.3f}".format(45.72793)→'+45.728'"{1:>10s}".format(8,"toto")→' toto'"{x!r}".format(x="I'm")→'"I\'m"'

☝ start default 0, �n not included in sequence, pas signed default 1

◽ Conversion : s (readable texte) or r (literal representation)

< > ^ = 0 at start for 8lling with 0integer: b binary, c char, d decimal (default), o octal, x or X hexa…Moat: e or E exponential, f or F 8xed point, g or G appropriate (default), string: s … % percent

◽ Formating :�ll char alignment sign mini width.precision~maxwidth type

+ - space

Operations on Dictionaries Operations on SetsOperators: | → union (vertical bar char) & → intersection - ^ → diNérence/symetric diN. < <= > >= → inclusion relationsOperators also exist as methods.

d.update(d2) update/add associations

Note: For dictionaries and sets, theseoperations use keys.

Speci�c to ordered sequences containers (lists, tuples, strings, bytes…)reversed(c)→ inversed iterator c*5→ duplicate c+c2→ concatenatec.index(val)→ position c.count(val)→ events count

Operations on Lists

d[key]=valued[key]→ value

d.keys()d.values()d.items()

d.clear()del d[key]

→iterable views onkeys/values/associations

Exa

mp

les

d.pop(key[,default])→ valued.popitem()→ (key,value)d.get(key[,default])→ valued.setdefault(key[,default])→value

s.update(s2) s.copy()s.add(key) s.remove(key)s.discard(key) s.clear()s.pop()

Loop Control

Go simultaneously on sequence's index and values:for idx,val in enumerate(lst):

☝ go

od

hab

it :

don

't m

odif

y lo

op

var

iable

Advanced: def fct(x,y,z,*args,a=3,b=5,**kwargs):

*args variable positional arguments (→tuple), default values, **kwargs variable named arguments (→dict)

one argument perparameter

storage/use of returned value

Algo:

f.flush() write cache

f.tell()→positionreading/writing progress sequentially in the �le, modi�able with:

f.seek(position[,origin])

f.truncate([taille]) resize

Formating

Advanced: *sequence **dict

s.startswith(pre�x[,start[,end]])s.endswith(suBx[,start[,end]]) s.strip([chars])s.count(sub[,start[,end]]) s.partition(sep)→ (before,sep,after)s.index(sub[,start[,end]]) s.find(sub[,start[,end]])s.is…() tests on chars categories (ex. s.isalpha())s.upper() s.lower() s.title() s.swapcase()s.casefold() s.capitalize() s.center([width,�ll]) s.ljust([width,�ll]) s.rjust([width,�ll]) s.zfill([width])s.encode(encoding) s.split([sep]) s.join(seq)

?yes

no

next

8nish…

Input

import copycopy.copy(c)→ shallow copy of containercopy.deepcopy(c)→ deep copy of container

☝ this is the use of function name with parenthesis which does the call

fct()

fct

fct

☝ text mode t by default (read/write str), possible binary mode b (read/write bytes). Convert from/to required type !

break immediate exitcontinue next iteration☝ else block for normal loop exit.

Cequiavaêtrevuaucours1:• Labouclewhile,breaketcontinue(?)

Page 10: ISUP-python Cours 1

"modele{} {} {}".format(x,y,r)

"{selection:formating!conversion}"

◽ Selection : 2 nom 0.nom 4[key] 0[2]

str

Displayprint("v=",3,"cm :",x,",",y+4)

print options: ◽ sep=" " items separator, default space◽ end="\n" end of print, default new line◽ file=sys.stdout print to 8le, default standard output

items to display : literal values, variables, expressions

loop on dict/set ⇔ loop on keys sequencesuse slices to loop on a subset of a sequence

Conditional Loop Statementstatements block executed as long ascondition is true

while logical condition: statements block

s = 0i = 1

while i <= 100: s = s + i**2 i = i + 1print("sum:",s)

initializations before the loop

condition with a least one variable value (here i)

s= ∑i=1

i=100

i2

☝ make condition variable change !

Iterative Loop Statementstatements block executed for each item of a container or iterator

for var in sequence: statements block

s = "Some text"cnt = 0

for c in s: if c == "e": cnt = cnt + 1print("found",cnt,"'e'")

Go over sequence's values

Algo: count number of e in the string.

Go over sequence's index◽ modify item at index◽ access items around index (before / after)lst = [11,18,9,12,23,4,17]lost = []for idx in range(len(lst)): val = lst[idx] if val > 15: lost.append(val) lst[idx] = 15print("modif:",lst,"-lost:",lost)

Algo: limit values greaterthan 15, memorizingof lost values.

☝ be

ware

of

in�

nite

loo

ps!

initializations before the loop

loop variable, assignment managed by for statement

Operations on Strings

values to formatformating directives

Integers Sequences

Files

s = input("Instructions:")☝ input always returns a string, convert it to required type

(cf. boxed Conversions on the other side).

range(5)→ 0 1 2 3 4 range(2,12,3)→ 2 5 8 11range(3,8)→ 3 4 5 6 7 range(20,5,-5)→ 20 15 10range(len(seq))→ sequence of index of values in seq ☝ range provides an immutable sequence of int constructed as needed

range([start,] end [,step])

f = open("file.txt","w",encoding="utf8")storing data on disk, and reading it back

opening mode◽ 'r' read◽ 'w' write◽ 'a' append◽ …'+' 'x' 'b' 't'

encoding ofchars for text�les: utf8 ascii latin1 …

name of 8leon disk(+path…)

8le variable for operations

f.write("coucou")f.writelines(list of lines)

writing readingf.read([n]) → next chars

if n not speci�ed, read up to end !f.readlines([n]) → list of next linesf.readline() → next line

with open(…) as f: for line in f : # processing ofline

cf. modules os, os.path and pathlib

f.close() ☝ dont forget to close the le after use !

Very common: opening with a guarded block (automatic closing) and reading loop on lines of a text 8le:

Function De�nition

def fct(x,y,z): """documentation""" # statements block, res computation, etc. return res

function name (identi8er)

result value of the call, if no computedresult to return: return None

☝ parameters and allvariables of this block exist only in the block and during the functioncall (think of a “black box”)

named parameters

Function Callr = fct(3,i+2,2*i)

Generic Operations on Containers

read empty string if end of �le

len(c)→ items countmin(c) max(c) sum(c)sorted(c)→ list sorted copyval in c → boolean, membership operator in (absence not in)enumerate(c)→ iterator on (index, value)zip(c1,c2…)→ iterator on tuples containing c

i items at same index

all(c)→ True if all c items evaluated to true, else Falseany(c)→ True if at least one item of c evaluated true, else False

☝ modify original list

lst.append(val) add item at endlst.extend(seq) add sequence of items at endlst.insert(idx,val) insert item at indexlst.remove(val) remove 8rst item with value vallst.pop([idx])→value remove & return item at index idx (default last)

lst.sort() lst.reverse() sort / reverse liste in place

"{:+2.3f}".format(45.72793)→'+45.728'"{1:>10s}".format(8,"toto")→' toto'"{x!r}".format(x="I'm")→'"I\'m"'

☝ start default 0, �n not included in sequence, pas signed default 1

◽ Conversion : s (readable texte) or r (literal representation)

< > ^ = 0 at start for 8lling with 0integer: b binary, c char, d decimal (default), o octal, x or X hexa…Moat: e or E exponential, f or F 8xed point, g or G appropriate (default), string: s … % percent

◽ Formating :�ll char alignment sign mini width.precision~maxwidth type

+ - space

Operations on Dictionaries Operations on SetsOperators: | → union (vertical bar char) & → intersection - ^ → diNérence/symetric diN. < <= > >= → inclusion relationsOperators also exist as methods.

d.update(d2) update/add associations

Note: For dictionaries and sets, theseoperations use keys.

Speci�c to ordered sequences containers (lists, tuples, strings, bytes…)reversed(c)→ inversed iterator c*5→ duplicate c+c2→ concatenatec.index(val)→ position c.count(val)→ events count

Operations on Lists

d[key]=valued[key]→ value

d.keys()d.values()d.items()

d.clear()del d[key]

→iterable views onkeys/values/associations

Exa

mp

les

d.pop(key[,default])→ valued.popitem()→ (key,value)d.get(key[,default])→ valued.setdefault(key[,default])→value

s.update(s2) s.copy()s.add(key) s.remove(key)s.discard(key) s.clear()s.pop()

Loop Control

Go simultaneously on sequence's index and values:for idx,val in enumerate(lst):

☝ go

od

hab

it :

don

't m

odif

y lo

op

var

iable

Advanced: def fct(x,y,z,*args,a=3,b=5,**kwargs):

*args variable positional arguments (→tuple), default values, **kwargs variable named arguments (→dict)

one argument perparameter

storage/use of returned value

Algo:

f.flush() write cache

f.tell()→positionreading/writing progress sequentially in the �le, modi�able with:

f.seek(position[,origin])

f.truncate([taille]) resize

Formating

Advanced: *sequence **dict

s.startswith(pre�x[,start[,end]])s.endswith(suBx[,start[,end]]) s.strip([chars])s.count(sub[,start[,end]]) s.partition(sep)→ (before,sep,after)s.index(sub[,start[,end]]) s.find(sub[,start[,end]])s.is…() tests on chars categories (ex. s.isalpha())s.upper() s.lower() s.title() s.swapcase()s.casefold() s.capitalize() s.center([width,�ll]) s.ljust([width,�ll]) s.rjust([width,�ll]) s.zfill([width])s.encode(encoding) s.split([sep]) s.join(seq)

?yes

no

next

8nish…

Input

import copycopy.copy(c)→ shallow copy of containercopy.deepcopy(c)→ deep copy of container

☝ this is the use of function name with parenthesis which does the call

fct()

fct

fct

☝ text mode t by default (read/write str), possible binary mode b (read/write bytes). Convert from/to required type !

break immediate exitcontinue next iteration☝ else block for normal loop exit.

Cequiavaêtrevuaucours1:• Labouclewhile,breaketcontinue(?)

• print simple

• input

Page 11: ISUP-python Cours 1

"modele{} {} {}".format(x,y,r)

"{selection:formating!conversion}"

◽ Selection : 2 nom 0.nom 4[key] 0[2]

str

Displayprint("v=",3,"cm :",x,",",y+4)

print options: ◽ sep=" " items separator, default space◽ end="\n" end of print, default new line◽ file=sys.stdout print to 8le, default standard output

items to display : literal values, variables, expressions

loop on dict/set ⇔ loop on keys sequencesuse slices to loop on a subset of a sequence

Conditional Loop Statementstatements block executed as long ascondition is true

while logical condition: statements block

s = 0i = 1

while i <= 100: s = s + i**2 i = i + 1print("sum:",s)

initializations before the loop

condition with a least one variable value (here i)

s= ∑i=1

i=100

i2

☝ make condition variable change !

Iterative Loop Statementstatements block executed for each item of a container or iterator

for var in sequence: statements block

s = "Some text"cnt = 0

for c in s: if c == "e": cnt = cnt + 1print("found",cnt,"'e'")

Go over sequence's values

Algo: count number of e in the string.

Go over sequence's index◽ modify item at index◽ access items around index (before / after)lst = [11,18,9,12,23,4,17]lost = []for idx in range(len(lst)): val = lst[idx] if val > 15: lost.append(val) lst[idx] = 15print("modif:",lst,"-lost:",lost)

Algo: limit values greaterthan 15, memorizingof lost values.

☝ be

ware

of

in�

nite

loo

ps!

initializations before the loop

loop variable, assignment managed by for statement

Operations on Strings

values to formatformating directives

Integers Sequences

Files

s = input("Instructions:")☝ input always returns a string, convert it to required type

(cf. boxed Conversions on the other side).

range(5)→ 0 1 2 3 4 range(2,12,3)→ 2 5 8 11range(3,8)→ 3 4 5 6 7 range(20,5,-5)→ 20 15 10range(len(seq))→ sequence of index of values in seq ☝ range provides an immutable sequence of int constructed as needed

range([start,] end [,step])

f = open("file.txt","w",encoding="utf8")storing data on disk, and reading it back

opening mode◽ 'r' read◽ 'w' write◽ 'a' append◽ …'+' 'x' 'b' 't'

encoding ofchars for text�les: utf8 ascii latin1 …

name of 8leon disk(+path…)

8le variable for operations

f.write("coucou")f.writelines(list of lines)

writing readingf.read([n]) → next chars

if n not speci�ed, read up to end !f.readlines([n]) → list of next linesf.readline() → next line

with open(…) as f: for line in f : # processing ofline

cf. modules os, os.path and pathlib

f.close() ☝ dont forget to close the le after use !

Very common: opening with a guarded block (automatic closing) and reading loop on lines of a text 8le:

Function De�nition

def fct(x,y,z): """documentation""" # statements block, res computation, etc. return res

function name (identi8er)

result value of the call, if no computedresult to return: return None

☝ parameters and allvariables of this block exist only in the block and during the functioncall (think of a “black box”)

named parameters

Function Callr = fct(3,i+2,2*i)

Generic Operations on Containers

read empty string if end of �le

len(c)→ items countmin(c) max(c) sum(c)sorted(c)→ list sorted copyval in c → boolean, membership operator in (absence not in)enumerate(c)→ iterator on (index, value)zip(c1,c2…)→ iterator on tuples containing c

i items at same index

all(c)→ True if all c items evaluated to true, else Falseany(c)→ True if at least one item of c evaluated true, else False

☝ modify original list

lst.append(val) add item at endlst.extend(seq) add sequence of items at endlst.insert(idx,val) insert item at indexlst.remove(val) remove 8rst item with value vallst.pop([idx])→value remove & return item at index idx (default last)

lst.sort() lst.reverse() sort / reverse liste in place

"{:+2.3f}".format(45.72793)→'+45.728'"{1:>10s}".format(8,"toto")→' toto'"{x!r}".format(x="I'm")→'"I\'m"'

☝ start default 0, �n not included in sequence, pas signed default 1

◽ Conversion : s (readable texte) or r (literal representation)

< > ^ = 0 at start for 8lling with 0integer: b binary, c char, d decimal (default), o octal, x or X hexa…Moat: e or E exponential, f or F 8xed point, g or G appropriate (default), string: s … % percent

◽ Formating :�ll char alignment sign mini width.precision~maxwidth type

+ - space

Operations on Dictionaries Operations on SetsOperators: | → union (vertical bar char) & → intersection - ^ → diNérence/symetric diN. < <= > >= → inclusion relationsOperators also exist as methods.

d.update(d2) update/add associations

Note: For dictionaries and sets, theseoperations use keys.

Speci�c to ordered sequences containers (lists, tuples, strings, bytes…)reversed(c)→ inversed iterator c*5→ duplicate c+c2→ concatenatec.index(val)→ position c.count(val)→ events count

Operations on Lists

d[key]=valued[key]→ value

d.keys()d.values()d.items()

d.clear()del d[key]

→iterable views onkeys/values/associations

Exa

mp

les

d.pop(key[,default])→ valued.popitem()→ (key,value)d.get(key[,default])→ valued.setdefault(key[,default])→value

s.update(s2) s.copy()s.add(key) s.remove(key)s.discard(key) s.clear()s.pop()

Loop Control

Go simultaneously on sequence's index and values:for idx,val in enumerate(lst):

☝ go

od

hab

it :

don

't m

odif

y lo

op

var

iable

Advanced: def fct(x,y,z,*args,a=3,b=5,**kwargs):

*args variable positional arguments (→tuple), default values, **kwargs variable named arguments (→dict)

one argument perparameter

storage/use of returned value

Algo:

f.flush() write cache

f.tell()→positionreading/writing progress sequentially in the �le, modi�able with:

f.seek(position[,origin])

f.truncate([taille]) resize

Formating

Advanced: *sequence **dict

s.startswith(pre�x[,start[,end]])s.endswith(suBx[,start[,end]]) s.strip([chars])s.count(sub[,start[,end]]) s.partition(sep)→ (before,sep,after)s.index(sub[,start[,end]]) s.find(sub[,start[,end]])s.is…() tests on chars categories (ex. s.isalpha())s.upper() s.lower() s.title() s.swapcase()s.casefold() s.capitalize() s.center([width,�ll]) s.ljust([width,�ll]) s.rjust([width,�ll]) s.zfill([width])s.encode(encoding) s.split([sep]) s.join(seq)

?yes

no

next

8nish…

Input

import copycopy.copy(c)→ shallow copy of containercopy.deepcopy(c)→ deep copy of container

☝ this is the use of function name with parenthesis which does the call

fct()

fct

fct

☝ text mode t by default (read/write str), possible binary mode b (read/write bytes). Convert from/to required type !

break immediate exitcontinue next iteration☝ else block for normal loop exit.

Cequiavaêtrevuaucours1:• labouclewhile,breaketcontinue(?)

• print simple

• Input

• fonctionssimplesExemple,écrirelafonctionmax(a,b)Quellesquestionsseposer?

Page 12: ISUP-python Cours 1

"modele{} {} {}".format(x,y,r)

"{selection:formating!conversion}"

◽ Selection : 2 nom 0.nom 4[key] 0[2]

str

Displayprint("v=",3,"cm :",x,",",y+4)

print options: ◽ sep=" " items separator, default space◽ end="\n" end of print, default new line◽ file=sys.stdout print to 8le, default standard output

items to display : literal values, variables, expressions

loop on dict/set ⇔ loop on keys sequencesuse slices to loop on a subset of a sequence

Conditional Loop Statementstatements block executed as long ascondition is true

while logical condition: statements block

s = 0i = 1

while i <= 100: s = s + i**2 i = i + 1print("sum:",s)

initializations before the loop

condition with a least one variable value (here i)

s= ∑i=1

i=100

i2

☝ make condition variable change !

Iterative Loop Statementstatements block executed for each item of a container or iterator

for var in sequence: statements block

s = "Some text"cnt = 0

for c in s: if c == "e": cnt = cnt + 1print("found",cnt,"'e'")

Go over sequence's values

Algo: count number of e in the string.

Go over sequence's index◽ modify item at index◽ access items around index (before / after)lst = [11,18,9,12,23,4,17]lost = []for idx in range(len(lst)): val = lst[idx] if val > 15: lost.append(val) lst[idx] = 15print("modif:",lst,"-lost:",lost)

Algo: limit values greaterthan 15, memorizingof lost values.

☝ be

ware

of

in�

nite

loo

ps!

initializations before the loop

loop variable, assignment managed by for statement

Operations on Strings

values to formatformating directives

Integers Sequences

Files

s = input("Instructions:")☝ input always returns a string, convert it to required type

(cf. boxed Conversions on the other side).

range(5)→ 0 1 2 3 4 range(2,12,3)→ 2 5 8 11range(3,8)→ 3 4 5 6 7 range(20,5,-5)→ 20 15 10range(len(seq))→ sequence of index of values in seq ☝ range provides an immutable sequence of int constructed as needed

range([start,] end [,step])

f = open("file.txt","w",encoding="utf8")storing data on disk, and reading it back

opening mode◽ 'r' read◽ 'w' write◽ 'a' append◽ …'+' 'x' 'b' 't'

encoding ofchars for text�les: utf8 ascii latin1 …

name of 8leon disk(+path…)

8le variable for operations

f.write("coucou")f.writelines(list of lines)

writing readingf.read([n]) → next chars

if n not speci�ed, read up to end !f.readlines([n]) → list of next linesf.readline() → next line

with open(…) as f: for line in f : # processing ofline

cf. modules os, os.path and pathlib

f.close() ☝ dont forget to close the le after use !

Very common: opening with a guarded block (automatic closing) and reading loop on lines of a text 8le:

Function De�nition

def fct(x,y,z): """documentation""" # statements block, res computation, etc. return res

function name (identi8er)

result value of the call, if no computedresult to return: return None

☝ parameters and allvariables of this block exist only in the block and during the functioncall (think of a “black box”)

named parameters

Function Callr = fct(3,i+2,2*i)

Generic Operations on Containers

read empty string if end of �le

len(c)→ items countmin(c) max(c) sum(c)sorted(c)→ list sorted copyval in c → boolean, membership operator in (absence not in)enumerate(c)→ iterator on (index, value)zip(c1,c2…)→ iterator on tuples containing c

i items at same index

all(c)→ True if all c items evaluated to true, else Falseany(c)→ True if at least one item of c evaluated true, else False

☝ modify original list

lst.append(val) add item at endlst.extend(seq) add sequence of items at endlst.insert(idx,val) insert item at indexlst.remove(val) remove 8rst item with value vallst.pop([idx])→value remove & return item at index idx (default last)

lst.sort() lst.reverse() sort / reverse liste in place

"{:+2.3f}".format(45.72793)→'+45.728'"{1:>10s}".format(8,"toto")→' toto'"{x!r}".format(x="I'm")→'"I\'m"'

☝ start default 0, �n not included in sequence, pas signed default 1

◽ Conversion : s (readable texte) or r (literal representation)

< > ^ = 0 at start for 8lling with 0integer: b binary, c char, d decimal (default), o octal, x or X hexa…Moat: e or E exponential, f or F 8xed point, g or G appropriate (default), string: s … % percent

◽ Formating :�ll char alignment sign mini width.precision~maxwidth type

+ - space

Operations on Dictionaries Operations on SetsOperators: | → union (vertical bar char) & → intersection - ^ → diNérence/symetric diN. < <= > >= → inclusion relationsOperators also exist as methods.

d.update(d2) update/add associations

Note: For dictionaries and sets, theseoperations use keys.

Speci�c to ordered sequences containers (lists, tuples, strings, bytes…)reversed(c)→ inversed iterator c*5→ duplicate c+c2→ concatenatec.index(val)→ position c.count(val)→ events count

Operations on Lists

d[key]=valued[key]→ value

d.keys()d.values()d.items()

d.clear()del d[key]

→iterable views onkeys/values/associations

Exa

mp

les

d.pop(key[,default])→ valued.popitem()→ (key,value)d.get(key[,default])→ valued.setdefault(key[,default])→value

s.update(s2) s.copy()s.add(key) s.remove(key)s.discard(key) s.clear()s.pop()

Loop Control

Go simultaneously on sequence's index and values:for idx,val in enumerate(lst):

☝ go

od

hab

it :

don

't m

odif

y lo

op

var

iable

Advanced: def fct(x,y,z,*args,a=3,b=5,**kwargs):

*args variable positional arguments (→tuple), default values, **kwargs variable named arguments (→dict)

one argument perparameter

storage/use of returned value

Algo:

f.flush() write cache

f.tell()→positionreading/writing progress sequentially in the �le, modi�able with:

f.seek(position[,origin])

f.truncate([taille]) resize

Formating

Advanced: *sequence **dict

s.startswith(pre�x[,start[,end]])s.endswith(suBx[,start[,end]]) s.strip([chars])s.count(sub[,start[,end]]) s.partition(sep)→ (before,sep,after)s.index(sub[,start[,end]]) s.find(sub[,start[,end]])s.is…() tests on chars categories (ex. s.isalpha())s.upper() s.lower() s.title() s.swapcase()s.casefold() s.capitalize() s.center([width,�ll]) s.ljust([width,�ll]) s.rjust([width,�ll]) s.zfill([width])s.encode(encoding) s.split([sep]) s.join(seq)

?yes

no

next

8nish…

Input

import copycopy.copy(c)→ shallow copy of containercopy.deepcopy(c)→ deep copy of container

☝ this is the use of function name with parenthesis which does the call

fct()

fct

fct

☝ text mode t by default (read/write str), possible binary mode b (read/write bytes). Convert from/to required type !

break immediate exitcontinue next iteration☝ else block for normal loop exit.

Cequiavaêtrevuaucours1:• labouclewhile,breaketcontinue(?)

• print simple

• Input

• fonctionssimplesExemple,écrirelafonctionmax(a,b)Quellesquestionsseposer?• Entrées/Sorties• Commentfairecequiestdemandé• Commenttester

Page 13: ISUP-python Cours 1

"modele{} {} {}".format(x,y,r)

"{selection:formating!conversion}"

◽ Selection : 2 nom 0.nom 4[key] 0[2]

str

Displayprint("v=",3,"cm :",x,",",y+4)

print options: ◽ sep=" " items separator, default space◽ end="\n" end of print, default new line◽ file=sys.stdout print to 8le, default standard output

items to display : literal values, variables, expressions

loop on dict/set ⇔ loop on keys sequencesuse slices to loop on a subset of a sequence

Conditional Loop Statementstatements block executed as long ascondition is true

while logical condition: statements block

s = 0i = 1

while i <= 100: s = s + i**2 i = i + 1print("sum:",s)

initializations before the loop

condition with a least one variable value (here i)

s= ∑i=1

i=100

i2

☝ make condition variable change !

Iterative Loop Statementstatements block executed for each item of a container or iterator

for var in sequence: statements block

s = "Some text"cnt = 0

for c in s: if c == "e": cnt = cnt + 1print("found",cnt,"'e'")

Go over sequence's values

Algo: count number of e in the string.

Go over sequence's index◽ modify item at index◽ access items around index (before / after)lst = [11,18,9,12,23,4,17]lost = []for idx in range(len(lst)): val = lst[idx] if val > 15: lost.append(val) lst[idx] = 15print("modif:",lst,"-lost:",lost)

Algo: limit values greaterthan 15, memorizingof lost values.

☝ be

ware

of

in�

nite

loo

ps!

initializations before the loop

loop variable, assignment managed by for statement

Operations on Strings

values to formatformating directives

Integers Sequences

Files

s = input("Instructions:")☝ input always returns a string, convert it to required type

(cf. boxed Conversions on the other side).

range(5)→ 0 1 2 3 4 range(2,12,3)→ 2 5 8 11range(3,8)→ 3 4 5 6 7 range(20,5,-5)→ 20 15 10range(len(seq))→ sequence of index of values in seq ☝ range provides an immutable sequence of int constructed as needed

range([start,] end [,step])

f = open("file.txt","w",encoding="utf8")storing data on disk, and reading it back

opening mode◽ 'r' read◽ 'w' write◽ 'a' append◽ …'+' 'x' 'b' 't'

encoding ofchars for text�les: utf8 ascii latin1 …

name of 8leon disk(+path…)

8le variable for operations

f.write("coucou")f.writelines(list of lines)

writing readingf.read([n]) → next chars

if n not speci�ed, read up to end !f.readlines([n]) → list of next linesf.readline() → next line

with open(…) as f: for line in f : # processing ofline

cf. modules os, os.path and pathlib

f.close() ☝ dont forget to close the le after use !

Very common: opening with a guarded block (automatic closing) and reading loop on lines of a text 8le:

Function De�nition

def fct(x,y,z): """documentation""" # statements block, res computation, etc. return res

function name (identi8er)

result value of the call, if no computedresult to return: return None

☝ parameters and allvariables of this block exist only in the block and during the functioncall (think of a “black box”)

named parameters

Function Callr = fct(3,i+2,2*i)

Generic Operations on Containers

read empty string if end of �le

len(c)→ items countmin(c) max(c) sum(c)sorted(c)→ list sorted copyval in c → boolean, membership operator in (absence not in)enumerate(c)→ iterator on (index, value)zip(c1,c2…)→ iterator on tuples containing c

i items at same index

all(c)→ True if all c items evaluated to true, else Falseany(c)→ True if at least one item of c evaluated true, else False

☝ modify original list

lst.append(val) add item at endlst.extend(seq) add sequence of items at endlst.insert(idx,val) insert item at indexlst.remove(val) remove 8rst item with value vallst.pop([idx])→value remove & return item at index idx (default last)

lst.sort() lst.reverse() sort / reverse liste in place

"{:+2.3f}".format(45.72793)→'+45.728'"{1:>10s}".format(8,"toto")→' toto'"{x!r}".format(x="I'm")→'"I\'m"'

☝ start default 0, �n not included in sequence, pas signed default 1

◽ Conversion : s (readable texte) or r (literal representation)

< > ^ = 0 at start for 8lling with 0integer: b binary, c char, d decimal (default), o octal, x or X hexa…Moat: e or E exponential, f or F 8xed point, g or G appropriate (default), string: s … % percent

◽ Formating :�ll char alignment sign mini width.precision~maxwidth type

+ - space

Operations on Dictionaries Operations on SetsOperators: | → union (vertical bar char) & → intersection - ^ → diNérence/symetric diN. < <= > >= → inclusion relationsOperators also exist as methods.

d.update(d2) update/add associations

Note: For dictionaries and sets, theseoperations use keys.

Speci�c to ordered sequences containers (lists, tuples, strings, bytes…)reversed(c)→ inversed iterator c*5→ duplicate c+c2→ concatenatec.index(val)→ position c.count(val)→ events count

Operations on Lists

d[key]=valued[key]→ value

d.keys()d.values()d.items()

d.clear()del d[key]

→iterable views onkeys/values/associations

Exa

mp

les

d.pop(key[,default])→ valued.popitem()→ (key,value)d.get(key[,default])→ valued.setdefault(key[,default])→value

s.update(s2) s.copy()s.add(key) s.remove(key)s.discard(key) s.clear()s.pop()

Loop Control

Go simultaneously on sequence's index and values:for idx,val in enumerate(lst):

☝ go

od

hab

it :

don

't m

odif

y lo

op

var

iable

Advanced: def fct(x,y,z,*args,a=3,b=5,**kwargs):

*args variable positional arguments (→tuple), default values, **kwargs variable named arguments (→dict)

one argument perparameter

storage/use of returned value

Algo:

f.flush() write cache

f.tell()→positionreading/writing progress sequentially in the �le, modi�able with:

f.seek(position[,origin])

f.truncate([taille]) resize

Formating

Advanced: *sequence **dict

s.startswith(pre�x[,start[,end]])s.endswith(suBx[,start[,end]]) s.strip([chars])s.count(sub[,start[,end]]) s.partition(sep)→ (before,sep,after)s.index(sub[,start[,end]]) s.find(sub[,start[,end]])s.is…() tests on chars categories (ex. s.isalpha())s.upper() s.lower() s.title() s.swapcase()s.casefold() s.capitalize() s.center([width,�ll]) s.ljust([width,�ll]) s.rjust([width,�ll]) s.zfill([width])s.encode(encoding) s.split([sep]) s.join(seq)

?yes

no

next

8nish…

Input

import copycopy.copy(c)→ shallow copy of containercopy.deepcopy(c)→ deep copy of container

☝ this is the use of function name with parenthesis which does the call

fct()

fct

fct

☝ text mode t by default (read/write str), possible binary mode b (read/write bytes). Convert from/to required type !

break immediate exitcontinue next iteration☝ else block for normal loop exit.

Cequiavaêtrevuaucours1:• labouclewhile,breaketcontinue(?)

• print simple

• Input

• fonctionssimples

Ecrirelafonctionaire_triangle(a,b,c):

Remarque : nous verrons que le calcul de l’aire nécessite d’utiliser la division classique (enpython, x divisé par y s’écrit : x / y) ainsi que la fonction de calcul d’une racine carrée (enpython, racine carrée de x s’écrit : math.sqrt(x)). Ces deux opérations retournent des valeursde type float, le résultat du calcul de l’aire est donc forcément flottant.

Nous pouvons traduire ces réponses sous la forme de la spécification suivante :

def aire_triangle(a,b,c):""" Number * Number * Number -> float

hypothèse : (a>0) and (b>0) and (c>0)hypothèse : les côtés a, b et c définissent bien un triangle.

retourne l�aire du triangle dont les côtés sont de longueur a, b, et c."""

3.2.1.2 Etape 2 : implémentation de l’algorithme de calcul Dans cette étape, ondoit maintenant trouver l’algorithme de calcul permettant de résoudre le problème posé. Engénéral, c’est l’étape la plus di�cile car elle demande souvent des connaissances (connaître desalgorithmes proches ou similaires qui doivent être adaptés), de l’imagination (pour trouver denouvelles approches de résolution) et de nombreux essais (au brouillon) avant d’arriver à larésoudre.

De nombreux algorithmes sont également décrits dans diverses sources : ouvrages d’algorithmique,sites internet spécialisés, Wikipedia, etc. Il faut parfois aussi inventer de nouveaux algorithmes.Nous verrons dans le cadre de ce cours certains algorithmes relativement complexes, mais pourl’instant, nous nous limitons à des algorithmes de calcul simples.

Le calcul de l’aire d’un triangle correspond à une simple expression paramétrée.

Cette formule a été inventée, selon la légende, par Héron d’Alexandrie au premier siècle de notreère. D’après la page Wikipedia (en date du 28 août 2014) dédiée à cet illustre ingénieur :

Formule de Héron

Cette formule permet de calculer l’aire d’un triangle en connaissant la longueur de ses côtés,sans utiliser la hauteur.

Soit ABC un triangle quelconque ayant pour longueurs des côtés a, b et c.

A partir de la valeur du demi-périmètre p = a + b + c

2 , l’aire du triangle est donnée par :

Aire =

p(p ≠ a)(p ≠ b)(p ≠ c)

Une première traduction possible de cette formule en Python est la suivante :

32

Page 14: ISUP-python Cours 1

"modele{} {} {}".format(x,y,r)

"{selection:formating!conversion}"

◽ Selection : 2 nom 0.nom 4[key] 0[2]

str

Displayprint("v=",3,"cm :",x,",",y+4)

print options: ◽ sep=" " items separator, default space◽ end="\n" end of print, default new line◽ file=sys.stdout print to 8le, default standard output

items to display : literal values, variables, expressions

loop on dict/set ⇔ loop on keys sequencesuse slices to loop on a subset of a sequence

Conditional Loop Statementstatements block executed as long ascondition is true

while logical condition: statements block

s = 0i = 1

while i <= 100: s = s + i**2 i = i + 1print("sum:",s)

initializations before the loop

condition with a least one variable value (here i)

s= ∑i=1

i=100

i2

☝ make condition variable change !

Iterative Loop Statementstatements block executed for each item of a container or iterator

for var in sequence: statements block

s = "Some text"cnt = 0

for c in s: if c == "e": cnt = cnt + 1print("found",cnt,"'e'")

Go over sequence's values

Algo: count number of e in the string.

Go over sequence's index◽ modify item at index◽ access items around index (before / after)lst = [11,18,9,12,23,4,17]lost = []for idx in range(len(lst)): val = lst[idx] if val > 15: lost.append(val) lst[idx] = 15print("modif:",lst,"-lost:",lost)

Algo: limit values greaterthan 15, memorizingof lost values.

☝ be

ware

of

in�

nite

loo

ps!

initializations before the loop

loop variable, assignment managed by for statement

Operations on Strings

values to formatformating directives

Integers Sequences

Files

s = input("Instructions:")☝ input always returns a string, convert it to required type

(cf. boxed Conversions on the other side).

range(5)→ 0 1 2 3 4 range(2,12,3)→ 2 5 8 11range(3,8)→ 3 4 5 6 7 range(20,5,-5)→ 20 15 10range(len(seq))→ sequence of index of values in seq ☝ range provides an immutable sequence of int constructed as needed

range([start,] end [,step])

f = open("file.txt","w",encoding="utf8")storing data on disk, and reading it back

opening mode◽ 'r' read◽ 'w' write◽ 'a' append◽ …'+' 'x' 'b' 't'

encoding ofchars for text�les: utf8 ascii latin1 …

name of 8leon disk(+path…)

8le variable for operations

f.write("coucou")f.writelines(list of lines)

writing readingf.read([n]) → next chars

if n not speci�ed, read up to end !f.readlines([n]) → list of next linesf.readline() → next line

with open(…) as f: for line in f : # processing ofline

cf. modules os, os.path and pathlib

f.close() ☝ dont forget to close the le after use !

Very common: opening with a guarded block (automatic closing) and reading loop on lines of a text 8le:

Function De�nition

def fct(x,y,z): """documentation""" # statements block, res computation, etc. return res

function name (identi8er)

result value of the call, if no computedresult to return: return None

☝ parameters and allvariables of this block exist only in the block and during the functioncall (think of a “black box”)

named parameters

Function Callr = fct(3,i+2,2*i)

Generic Operations on Containers

read empty string if end of �le

len(c)→ items countmin(c) max(c) sum(c)sorted(c)→ list sorted copyval in c → boolean, membership operator in (absence not in)enumerate(c)→ iterator on (index, value)zip(c1,c2…)→ iterator on tuples containing c

i items at same index

all(c)→ True if all c items evaluated to true, else Falseany(c)→ True if at least one item of c evaluated true, else False

☝ modify original list

lst.append(val) add item at endlst.extend(seq) add sequence of items at endlst.insert(idx,val) insert item at indexlst.remove(val) remove 8rst item with value vallst.pop([idx])→value remove & return item at index idx (default last)

lst.sort() lst.reverse() sort / reverse liste in place

"{:+2.3f}".format(45.72793)→'+45.728'"{1:>10s}".format(8,"toto")→' toto'"{x!r}".format(x="I'm")→'"I\'m"'

☝ start default 0, �n not included in sequence, pas signed default 1

◽ Conversion : s (readable texte) or r (literal representation)

< > ^ = 0 at start for 8lling with 0integer: b binary, c char, d decimal (default), o octal, x or X hexa…Moat: e or E exponential, f or F 8xed point, g or G appropriate (default), string: s … % percent

◽ Formating :�ll char alignment sign mini width.precision~maxwidth type

+ - space

Operations on Dictionaries Operations on SetsOperators: | → union (vertical bar char) & → intersection - ^ → diNérence/symetric diN. < <= > >= → inclusion relationsOperators also exist as methods.

d.update(d2) update/add associations

Note: For dictionaries and sets, theseoperations use keys.

Speci�c to ordered sequences containers (lists, tuples, strings, bytes…)reversed(c)→ inversed iterator c*5→ duplicate c+c2→ concatenatec.index(val)→ position c.count(val)→ events count

Operations on Lists

d[key]=valued[key]→ value

d.keys()d.values()d.items()

d.clear()del d[key]

→iterable views onkeys/values/associations

Exa

mp

les

d.pop(key[,default])→ valued.popitem()→ (key,value)d.get(key[,default])→ valued.setdefault(key[,default])→value

s.update(s2) s.copy()s.add(key) s.remove(key)s.discard(key) s.clear()s.pop()

Loop Control

Go simultaneously on sequence's index and values:for idx,val in enumerate(lst):

☝ go

od

hab

it :

don

't m

odif

y lo

op

var

iable

Advanced: def fct(x,y,z,*args,a=3,b=5,**kwargs):

*args variable positional arguments (→tuple), default values, **kwargs variable named arguments (→dict)

one argument perparameter

storage/use of returned value

Algo:

f.flush() write cache

f.tell()→positionreading/writing progress sequentially in the �le, modi�able with:

f.seek(position[,origin])

f.truncate([taille]) resize

Formating

Advanced: *sequence **dict

s.startswith(pre�x[,start[,end]])s.endswith(suBx[,start[,end]]) s.strip([chars])s.count(sub[,start[,end]]) s.partition(sep)→ (before,sep,after)s.index(sub[,start[,end]]) s.find(sub[,start[,end]])s.is…() tests on chars categories (ex. s.isalpha())s.upper() s.lower() s.title() s.swapcase()s.casefold() s.capitalize() s.center([width,�ll]) s.ljust([width,�ll]) s.rjust([width,�ll]) s.zfill([width])s.encode(encoding) s.split([sep]) s.join(seq)

?yes

no

next

8nish…

Input

import copycopy.copy(c)→ shallow copy of containercopy.deepcopy(c)→ deep copy of container

☝ this is the use of function name with parenthesis which does the call

fct()

fct

fct

☝ text mode t by default (read/write str), possible binary mode b (read/write bytes). Convert from/to required type !

break immediate exitcontinue next iteration☝ else block for normal loop exit.

Cequiavaêtrevuaucours1:• labouclewhile,breaketcontinue(?)

• print simple

• Input

• fonctionssimplesExemple,écrirelafonctionmax(a,b)Quellesquestionsseposer?• Entrées/Sorties• Commentfairecequiestdemandé• Commenttester

def max(a, b):"""Number * Number -> Numberretourne le maximum des nombres a et b."""if a>b:return a

elsereturn b

max(4,5)max(5,4)

Page 15: ISUP-python Cours 1

"modele{} {} {}".format(x,y,r)

"{selection:formating!conversion}"

◽ Selection : 2 nom 0.nom 4[key] 0[2]

str

Displayprint("v=",3,"cm :",x,",",y+4)

print options: ◽ sep=" " items separator, default space◽ end="\n" end of print, default new line◽ file=sys.stdout print to 8le, default standard output

items to display : literal values, variables, expressions

loop on dict/set ⇔ loop on keys sequencesuse slices to loop on a subset of a sequence

Conditional Loop Statementstatements block executed as long ascondition is true

while logical condition: statements block

s = 0i = 1

while i <= 100: s = s + i**2 i = i + 1print("sum:",s)

initializations before the loop

condition with a least one variable value (here i)

s= ∑i=1

i=100

i2

☝ make condition variable change !

Iterative Loop Statementstatements block executed for each item of a container or iterator

for var in sequence: statements block

s = "Some text"cnt = 0

for c in s: if c == "e": cnt = cnt + 1print("found",cnt,"'e'")

Go over sequence's values

Algo: count number of e in the string.

Go over sequence's index◽ modify item at index◽ access items around index (before / after)lst = [11,18,9,12,23,4,17]lost = []for idx in range(len(lst)): val = lst[idx] if val > 15: lost.append(val) lst[idx] = 15print("modif:",lst,"-lost:",lost)

Algo: limit values greaterthan 15, memorizingof lost values.

☝ be

ware

of

in�

nite

loo

ps!

initializations before the loop

loop variable, assignment managed by for statement

Operations on Strings

values to formatformating directives

Integers Sequences

Files

s = input("Instructions:")☝ input always returns a string, convert it to required type

(cf. boxed Conversions on the other side).

range(5)→ 0 1 2 3 4 range(2,12,3)→ 2 5 8 11range(3,8)→ 3 4 5 6 7 range(20,5,-5)→ 20 15 10range(len(seq))→ sequence of index of values in seq ☝ range provides an immutable sequence of int constructed as needed

range([start,] end [,step])

f = open("file.txt","w",encoding="utf8")storing data on disk, and reading it back

opening mode◽ 'r' read◽ 'w' write◽ 'a' append◽ …'+' 'x' 'b' 't'

encoding ofchars for text�les: utf8 ascii latin1 …

name of 8leon disk(+path…)

8le variable for operations

f.write("coucou")f.writelines(list of lines)

writing readingf.read([n]) → next chars

if n not speci�ed, read up to end !f.readlines([n]) → list of next linesf.readline() → next line

with open(…) as f: for line in f : # processing ofline

cf. modules os, os.path and pathlib

f.close() ☝ dont forget to close the le after use !

Very common: opening with a guarded block (automatic closing) and reading loop on lines of a text 8le:

Function De�nition

def fct(x,y,z): """documentation""" # statements block, res computation, etc. return res

function name (identi8er)

result value of the call, if no computedresult to return: return None

☝ parameters and allvariables of this block exist only in the block and during the functioncall (think of a “black box”)

named parameters

Function Callr = fct(3,i+2,2*i)

Generic Operations on Containers

read empty string if end of �le

len(c)→ items countmin(c) max(c) sum(c)sorted(c)→ list sorted copyval in c → boolean, membership operator in (absence not in)enumerate(c)→ iterator on (index, value)zip(c1,c2…)→ iterator on tuples containing c

i items at same index

all(c)→ True if all c items evaluated to true, else Falseany(c)→ True if at least one item of c evaluated true, else False

☝ modify original list

lst.append(val) add item at endlst.extend(seq) add sequence of items at endlst.insert(idx,val) insert item at indexlst.remove(val) remove 8rst item with value vallst.pop([idx])→value remove & return item at index idx (default last)

lst.sort() lst.reverse() sort / reverse liste in place

"{:+2.3f}".format(45.72793)→'+45.728'"{1:>10s}".format(8,"toto")→' toto'"{x!r}".format(x="I'm")→'"I\'m"'

☝ start default 0, �n not included in sequence, pas signed default 1

◽ Conversion : s (readable texte) or r (literal representation)

< > ^ = 0 at start for 8lling with 0integer: b binary, c char, d decimal (default), o octal, x or X hexa…Moat: e or E exponential, f or F 8xed point, g or G appropriate (default), string: s … % percent

◽ Formating :�ll char alignment sign mini width.precision~maxwidth type

+ - space

Operations on Dictionaries Operations on SetsOperators: | → union (vertical bar char) & → intersection - ^ → diNérence/symetric diN. < <= > >= → inclusion relationsOperators also exist as methods.

d.update(d2) update/add associations

Note: For dictionaries and sets, theseoperations use keys.

Speci�c to ordered sequences containers (lists, tuples, strings, bytes…)reversed(c)→ inversed iterator c*5→ duplicate c+c2→ concatenatec.index(val)→ position c.count(val)→ events count

Operations on Lists

d[key]=valued[key]→ value

d.keys()d.values()d.items()

d.clear()del d[key]

→iterable views onkeys/values/associations

Exa

mp

les

d.pop(key[,default])→ valued.popitem()→ (key,value)d.get(key[,default])→ valued.setdefault(key[,default])→value

s.update(s2) s.copy()s.add(key) s.remove(key)s.discard(key) s.clear()s.pop()

Loop Control

Go simultaneously on sequence's index and values:for idx,val in enumerate(lst):

☝ go

od

hab

it :

don

't m

odif

y lo

op

var

iable

Advanced: def fct(x,y,z,*args,a=3,b=5,**kwargs):

*args variable positional arguments (→tuple), default values, **kwargs variable named arguments (→dict)

one argument perparameter

storage/use of returned value

Algo:

f.flush() write cache

f.tell()→positionreading/writing progress sequentially in the �le, modi�able with:

f.seek(position[,origin])

f.truncate([taille]) resize

Formating

Advanced: *sequence **dict

s.startswith(pre�x[,start[,end]])s.endswith(suBx[,start[,end]]) s.strip([chars])s.count(sub[,start[,end]]) s.partition(sep)→ (before,sep,after)s.index(sub[,start[,end]]) s.find(sub[,start[,end]])s.is…() tests on chars categories (ex. s.isalpha())s.upper() s.lower() s.title() s.swapcase()s.casefold() s.capitalize() s.center([width,�ll]) s.ljust([width,�ll]) s.rjust([width,�ll]) s.zfill([width])s.encode(encoding) s.split([sep]) s.join(seq)

?yes

no

next

8nish…

Input

import copycopy.copy(c)→ shallow copy of containercopy.deepcopy(c)→ deep copy of container

☝ this is the use of function name with parenthesis which does the call

fct()

fct

fct

☝ text mode t by default (read/write str), possible binary mode b (read/write bytes). Convert from/to required type !

break immediate exitcontinue next iteration☝ else block for normal loop exit.

Cequiavaêtrevuaucours1:• labouclewhile,breaketcontinue(?)

• print simple

• Input

• fonctionssimples

Ecrirelafonctionperimetre(longueur,largeur)

Page 16: ISUP-python Cours 1

"modele{} {} {}".format(x,y,r)

"{selection:formating!conversion}"

◽ Selection : 2 nom 0.nom 4[key] 0[2]

str

Displayprint("v=",3,"cm :",x,",",y+4)

print options: ◽ sep=" " items separator, default space◽ end="\n" end of print, default new line◽ file=sys.stdout print to 8le, default standard output

items to display : literal values, variables, expressions

loop on dict/set ⇔ loop on keys sequencesuse slices to loop on a subset of a sequence

Conditional Loop Statementstatements block executed as long ascondition is true

while logical condition: statements block

s = 0i = 1

while i <= 100: s = s + i**2 i = i + 1print("sum:",s)

initializations before the loop

condition with a least one variable value (here i)

s= ∑i=1

i=100

i2

☝ make condition variable change !

Iterative Loop Statementstatements block executed for each item of a container or iterator

for var in sequence: statements block

s = "Some text"cnt = 0

for c in s: if c == "e": cnt = cnt + 1print("found",cnt,"'e'")

Go over sequence's values

Algo: count number of e in the string.

Go over sequence's index◽ modify item at index◽ access items around index (before / after)lst = [11,18,9,12,23,4,17]lost = []for idx in range(len(lst)): val = lst[idx] if val > 15: lost.append(val) lst[idx] = 15print("modif:",lst,"-lost:",lost)

Algo: limit values greaterthan 15, memorizingof lost values.

☝ be

ware

of

in�

nite

loo

ps!

initializations before the loop

loop variable, assignment managed by for statement

Operations on Strings

values to formatformating directives

Integers Sequences

Files

s = input("Instructions:")☝ input always returns a string, convert it to required type

(cf. boxed Conversions on the other side).

range(5)→ 0 1 2 3 4 range(2,12,3)→ 2 5 8 11range(3,8)→ 3 4 5 6 7 range(20,5,-5)→ 20 15 10range(len(seq))→ sequence of index of values in seq ☝ range provides an immutable sequence of int constructed as needed

range([start,] end [,step])

f = open("file.txt","w",encoding="utf8")storing data on disk, and reading it back

opening mode◽ 'r' read◽ 'w' write◽ 'a' append◽ …'+' 'x' 'b' 't'

encoding ofchars for text�les: utf8 ascii latin1 …

name of 8leon disk(+path…)

8le variable for operations

f.write("coucou")f.writelines(list of lines)

writing readingf.read([n]) → next chars

if n not speci�ed, read up to end !f.readlines([n]) → list of next linesf.readline() → next line

with open(…) as f: for line in f : # processing ofline

cf. modules os, os.path and pathlib

f.close() ☝ dont forget to close the le after use !

Very common: opening with a guarded block (automatic closing) and reading loop on lines of a text 8le:

Function De�nition

def fct(x,y,z): """documentation""" # statements block, res computation, etc. return res

function name (identi8er)

result value of the call, if no computedresult to return: return None

☝ parameters and allvariables of this block exist only in the block and during the functioncall (think of a “black box”)

named parameters

Function Callr = fct(3,i+2,2*i)

Generic Operations on Containers

read empty string if end of �le

len(c)→ items countmin(c) max(c) sum(c)sorted(c)→ list sorted copyval in c → boolean, membership operator in (absence not in)enumerate(c)→ iterator on (index, value)zip(c1,c2…)→ iterator on tuples containing c

i items at same index

all(c)→ True if all c items evaluated to true, else Falseany(c)→ True if at least one item of c evaluated true, else False

☝ modify original list

lst.append(val) add item at endlst.extend(seq) add sequence of items at endlst.insert(idx,val) insert item at indexlst.remove(val) remove 8rst item with value vallst.pop([idx])→value remove & return item at index idx (default last)

lst.sort() lst.reverse() sort / reverse liste in place

"{:+2.3f}".format(45.72793)→'+45.728'"{1:>10s}".format(8,"toto")→' toto'"{x!r}".format(x="I'm")→'"I\'m"'

☝ start default 0, �n not included in sequence, pas signed default 1

◽ Conversion : s (readable texte) or r (literal representation)

< > ^ = 0 at start for 8lling with 0integer: b binary, c char, d decimal (default), o octal, x or X hexa…Moat: e or E exponential, f or F 8xed point, g or G appropriate (default), string: s … % percent

◽ Formating :�ll char alignment sign mini width.precision~maxwidth type

+ - space

Operations on Dictionaries Operations on SetsOperators: | → union (vertical bar char) & → intersection - ^ → diNérence/symetric diN. < <= > >= → inclusion relationsOperators also exist as methods.

d.update(d2) update/add associations

Note: For dictionaries and sets, theseoperations use keys.

Speci�c to ordered sequences containers (lists, tuples, strings, bytes…)reversed(c)→ inversed iterator c*5→ duplicate c+c2→ concatenatec.index(val)→ position c.count(val)→ events count

Operations on Lists

d[key]=valued[key]→ value

d.keys()d.values()d.items()

d.clear()del d[key]

→iterable views onkeys/values/associations

Exa

mp

les

d.pop(key[,default])→ valued.popitem()→ (key,value)d.get(key[,default])→ valued.setdefault(key[,default])→value

s.update(s2) s.copy()s.add(key) s.remove(key)s.discard(key) s.clear()s.pop()

Loop Control

Go simultaneously on sequence's index and values:for idx,val in enumerate(lst):

☝ go

od

hab

it :

don

't m

odif

y lo

op

var

iable

Advanced: def fct(x,y,z,*args,a=3,b=5,**kwargs):

*args variable positional arguments (→tuple), default values, **kwargs variable named arguments (→dict)

one argument perparameter

storage/use of returned value

Algo:

f.flush() write cache

f.tell()→positionreading/writing progress sequentially in the �le, modi�able with:

f.seek(position[,origin])

f.truncate([taille]) resize

Formating

Advanced: *sequence **dict

s.startswith(pre�x[,start[,end]])s.endswith(suBx[,start[,end]]) s.strip([chars])s.count(sub[,start[,end]]) s.partition(sep)→ (before,sep,after)s.index(sub[,start[,end]]) s.find(sub[,start[,end]])s.is…() tests on chars categories (ex. s.isalpha())s.upper() s.lower() s.title() s.swapcase()s.casefold() s.capitalize() s.center([width,�ll]) s.ljust([width,�ll]) s.rjust([width,�ll]) s.zfill([width])s.encode(encoding) s.split([sep]) s.join(seq)

?yes

no

next

8nish…

Input

import copycopy.copy(c)→ shallow copy of containercopy.deepcopy(c)→ deep copy of container

☝ this is the use of function name with parenthesis which does the call

fct()

fct

fct

☝ text mode t by default (read/write str), possible binary mode b (read/write bytes). Convert from/to required type !

break immediate exitcontinue next iteration☝ else block for normal loop exit.

Cequiavaêtrevuaucours1:• labouclewhile,breaketcontinue(?)

• print simple

• Input

• fonctionssimples

Ecrirelesfonctionsvaleur_absolue(x),est_divisible(n,m),max(a,b,c)

Page 17: ISUP-python Cours 1

"modele{} {} {}".format(x,y,r)

"{selection:formating!conversion}"

◽ Selection : 2 nom 0.nom 4[key] 0[2]

str

Displayprint("v=",3,"cm :",x,",",y+4)

print options: ◽ sep=" " items separator, default space◽ end="\n" end of print, default new line◽ file=sys.stdout print to 8le, default standard output

items to display : literal values, variables, expressions

loop on dict/set ⇔ loop on keys sequencesuse slices to loop on a subset of a sequence

Conditional Loop Statementstatements block executed as long ascondition is true

while logical condition: statements block

s = 0i = 1

while i <= 100: s = s + i**2 i = i + 1print("sum:",s)

initializations before the loop

condition with a least one variable value (here i)

s= ∑i=1

i=100

i2

☝ make condition variable change !

Iterative Loop Statementstatements block executed for each item of a container or iterator

for var in sequence: statements block

s = "Some text"cnt = 0

for c in s: if c == "e": cnt = cnt + 1print("found",cnt,"'e'")

Go over sequence's values

Algo: count number of e in the string.

Go over sequence's index◽ modify item at index◽ access items around index (before / after)lst = [11,18,9,12,23,4,17]lost = []for idx in range(len(lst)): val = lst[idx] if val > 15: lost.append(val) lst[idx] = 15print("modif:",lst,"-lost:",lost)

Algo: limit values greaterthan 15, memorizingof lost values.

☝ be

ware

of

in�

nite

loo

ps!

initializations before the loop

loop variable, assignment managed by for statement

Operations on Strings

values to formatformating directives

Integers Sequences

Files

s = input("Instructions:")☝ input always returns a string, convert it to required type

(cf. boxed Conversions on the other side).

range(5)→ 0 1 2 3 4 range(2,12,3)→ 2 5 8 11range(3,8)→ 3 4 5 6 7 range(20,5,-5)→ 20 15 10range(len(seq))→ sequence of index of values in seq ☝ range provides an immutable sequence of int constructed as needed

range([start,] end [,step])

f = open("file.txt","w",encoding="utf8")storing data on disk, and reading it back

opening mode◽ 'r' read◽ 'w' write◽ 'a' append◽ …'+' 'x' 'b' 't'

encoding ofchars for text�les: utf8 ascii latin1 …

name of 8leon disk(+path…)

8le variable for operations

f.write("coucou")f.writelines(list of lines)

writing readingf.read([n]) → next chars

if n not speci�ed, read up to end !f.readlines([n]) → list of next linesf.readline() → next line

with open(…) as f: for line in f : # processing ofline

cf. modules os, os.path and pathlib

f.close() ☝ dont forget to close the le after use !

Very common: opening with a guarded block (automatic closing) and reading loop on lines of a text 8le:

Function De�nition

def fct(x,y,z): """documentation""" # statements block, res computation, etc. return res

function name (identi8er)

result value of the call, if no computedresult to return: return None

☝ parameters and allvariables of this block exist only in the block and during the functioncall (think of a “black box”)

named parameters

Function Callr = fct(3,i+2,2*i)

Generic Operations on Containers

read empty string if end of �le

len(c)→ items countmin(c) max(c) sum(c)sorted(c)→ list sorted copyval in c → boolean, membership operator in (absence not in)enumerate(c)→ iterator on (index, value)zip(c1,c2…)→ iterator on tuples containing c

i items at same index

all(c)→ True if all c items evaluated to true, else Falseany(c)→ True if at least one item of c evaluated true, else False

☝ modify original list

lst.append(val) add item at endlst.extend(seq) add sequence of items at endlst.insert(idx,val) insert item at indexlst.remove(val) remove 8rst item with value vallst.pop([idx])→value remove & return item at index idx (default last)

lst.sort() lst.reverse() sort / reverse liste in place

"{:+2.3f}".format(45.72793)→'+45.728'"{1:>10s}".format(8,"toto")→' toto'"{x!r}".format(x="I'm")→'"I\'m"'

☝ start default 0, �n not included in sequence, pas signed default 1

◽ Conversion : s (readable texte) or r (literal representation)

< > ^ = 0 at start for 8lling with 0integer: b binary, c char, d decimal (default), o octal, x or X hexa…Moat: e or E exponential, f or F 8xed point, g or G appropriate (default), string: s … % percent

◽ Formating :�ll char alignment sign mini width.precision~maxwidth type

+ - space

Operations on Dictionaries Operations on SetsOperators: | → union (vertical bar char) & → intersection - ^ → diNérence/symetric diN. < <= > >= → inclusion relationsOperators also exist as methods.

d.update(d2) update/add associations

Note: For dictionaries and sets, theseoperations use keys.

Speci�c to ordered sequences containers (lists, tuples, strings, bytes…)reversed(c)→ inversed iterator c*5→ duplicate c+c2→ concatenatec.index(val)→ position c.count(val)→ events count

Operations on Lists

d[key]=valued[key]→ value

d.keys()d.values()d.items()

d.clear()del d[key]

→iterable views onkeys/values/associations

Exa

mp

les

d.pop(key[,default])→ valued.popitem()→ (key,value)d.get(key[,default])→ valued.setdefault(key[,default])→value

s.update(s2) s.copy()s.add(key) s.remove(key)s.discard(key) s.clear()s.pop()

Loop Control

Go simultaneously on sequence's index and values:for idx,val in enumerate(lst):

☝ go

od

hab

it :

don

't m

odif

y lo

op

var

iable

Advanced: def fct(x,y,z,*args,a=3,b=5,**kwargs):

*args variable positional arguments (→tuple), default values, **kwargs variable named arguments (→dict)

one argument perparameter

storage/use of returned value

Algo:

f.flush() write cache

f.tell()→positionreading/writing progress sequentially in the �le, modi�able with:

f.seek(position[,origin])

f.truncate([taille]) resize

Formating

Advanced: *sequence **dict

s.startswith(pre�x[,start[,end]])s.endswith(suBx[,start[,end]]) s.strip([chars])s.count(sub[,start[,end]]) s.partition(sep)→ (before,sep,after)s.index(sub[,start[,end]]) s.find(sub[,start[,end]])s.is…() tests on chars categories (ex. s.isalpha())s.upper() s.lower() s.title() s.swapcase()s.casefold() s.capitalize() s.center([width,�ll]) s.ljust([width,�ll]) s.rjust([width,�ll]) s.zfill([width])s.encode(encoding) s.split([sep]) s.join(seq)

?yes

no

next

8nish…

Input

import copycopy.copy(c)→ shallow copy of containercopy.deepcopy(c)→ deep copy of container

☝ this is the use of function name with parenthesis which does the call

fct()

fct

fct

☝ text mode t by default (read/write str), possible binary mode b (read/write bytes). Convert from/to required type !

break immediate exitcontinue next iteration☝ else block for normal loop exit.

Cequiavaêtrevuaucours1:• labouclewhile,breaketcontinue(?)

• print simple

• Input

• fonctionssimples

Ecrirelesfonctionssomme_entiers(n),factorielle(n),pgcd(a,b)

i après le tour vaut 6------------------sortie=====================15

Important : dans ce cours, nous n’utiliserons print que pendant les travaux sur machine, etuniquement dans le but d’a�cher des traces d’exécution.

4.3 Problèmes numériques

La boucle while est notamment utilisée pour e�ectuer des calculs répétitifs sur les nombresentiers ou flottants.

Nous allons nous intéresser dans cette section aux problèmes suivants :

— calcul des éléments d’une suite— calcul d’une somme (série numérique) ou d’un produit— un exemple de problème plus complexe : le calcul du PGCD de deux entiers naturels— un problème nécessitant des boucles imbriquées : le nombre de couples d’entiers distincts

dans un intervalle

4.3.1 Calcul des éléments d’une suite

Une suite arithmétique (un

)nØ0 est généralement définie en mathématiques de la façon suivante

:

;u0 = k

u

n

= f(un≠1) pour n > 0

où k est une constante dite condition initiale de la suite, et f est une fonction permettant decalculer l’élément de la suite au rang n à partir de la valeur de l’élément de rang n ≠ 1. On ditd’une telle définition qu’elle est récursive.

Considérons en guise d’exemple la suite récursive (un

)nØ0 ci-dessous :

;u0 = 7u

n

= 2u

n≠1 + 3 pour n > 0

On peut définir, avec une boucle while, une fonction dont l’argument est n et qui calcule lavaleur de u

n

:

def suite_u(n):""" int -> int

Hypothèse: n >= 0

retourne la valeur au rang n de la suite U."""

62

Retourne le plus grand commun diviseur de a et b."""

# q : intq = a # le quotient

# r : intr = b # le diviseur

# temp : inttemp = 0 # variable temporaire

while r != 0:temp = q % rq = rr = temp

return q

# Jeu de testsassert pgcd(9, 3) == 3assert pgcd(15, 15) == 15assert pgcd(56, 42) == 14assert pgcd(4199, 1530) == 17

Exercices : donner la simulation correspondant à pgcd(56, 42). Même question pourpgcd(4199, 1530).

4.3.4 Boucles imbriquées : les couples d’entiers

Considérons la question suivante :

combien existe-t-il de couples (i, j) distincts d’entiers naturels inférieurs ou égaux àun entier n fixé ?

Pour répondre à cette question, on ne peut pas se contenter d’une unique boucle while car :

— nous devons considérer tous les entiers i de 0 à n

— pour chaque i nous devons considérer également tous les entiers j de 0 à n

Il est donc nécessaire de combiner deux boucles, l’une à l’intérieur de l’autre. On parle alors deboucles imbriquées.

Ceci se traduit par la fonction suivante :

def nb_couples_distincts(n):""" int -> int

hypothèse : n >= 0

67

def pgcd(a,b):""" int * int -> int

Hypothèse: (a >= b) and (b > 0)

Retourne le plus grand commun diviseur de a et b."""

Par exemple :

>>> pgcd(9, 3)3

>>> pgcd(15, 15)15

>>> pgcd(56, 42)14

>>> pgcd(4199, 1530)17

Pour écrire la fonction pgcd, nous allons exploiter une variante de l’algorithme d’Euclide. Pourcalculer le PGCD des deux entiers a et b tels que a Ø b :

— si b ”= 0 alors le PGCD de a et b est le PGCD de b et du reste dans la division euclidiennede a par b (a%b)

— sinon le PGCD de a et b est a.

Remarque: on vérifie aisément que si a Ø b et b ”= 0, alors on a b Ø a%b

Par exemple, le PGCD de 56 et 42 est égal :

— au PGCD de 42 et 56%42 = 14, qui est égal :— au PGCD de 14 et 42%14 = 0, donc le PGCD cherché est 14

Comme autre exemple, on peut calculer le PGCD de 4199 et 1530 qui est égal :

— au PGCD de 1530 et 4199%1530 = 1139, qui est égal :— au PGCD de 1139 et 1530%1139 = 391, qui est égal :— au PGCD de 391 et 1139%391 = 357, qui est égal :— au PGCD de 357 et 391%357 = 34, qui est égal :— au PGCD de 34 et 357%34 = 17, qui est égal :— au PGCD de 17 et 34%17 = 0, donc le PGCD cherché est 17 (ouf !).

Cet algorithme peut être traduit de la façon suivante en Python :

def pgcd(a,b):""" int * int -> int

Hypothèse: b > 0Hypothèse: a >= b

66