for i normal Python: Voltando aos Containers print(v=,3,cm ...jpaulo/ensino/TRS/P/TP02.pdf ·...

18
Python: Voltando aos Containers Existe um vasto leque de funções que facilitam as operações com containers: listas, conjuntos e dicionários. Generic Operations on Containers len(c)→ items count min(c) max(c) sum(c) sorted(c)list sorted copy val 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 False any(c)True if at least one item of c evaluated true, else False ☝ modify original list lst.append(val) add item at end lst.extend(seq) add sequence of items at end lst.insert(idx,val) insert item at index lst.remove(val) remove 8rst item with value val lst.pop([idx])→value remove & return item at index idx (default last) lst.sort() lst.reverse() sort / reverse liste in place Note: For dictionaries and sets, these operations use keys. Specic to ordered sequences containers (lists, tuples, strings, bytes…) reversed(c)→ inversed iterator c*5→ duplicate c+c2→ concatenate c.index(val)→ position c.count(val)→ events count Operations on Lists import copy copy.copy(c)→ shallow copy of container copy.deepcopy(c)→ deep copy of container >>> L=[4,6,1,7] >>> L [4, 6, 1, 7] >>> min(L) 1 >>> max(L) 7 >>> sorted(L) [1, 4, 6, 7] >>> L.pop() 7 >>> L [4, 6, 1] >>> 2*L [4, 6, 1, 4, 6, 1] >>> L.sort() >>> L [1, 4, 6]

Transcript of for i normal Python: Voltando aos Containers print(v=,3,cm ...jpaulo/ensino/TRS/P/TP02.pdf ·...

Python: Voltando aos Containers❖ Existe um vasto leque de funções que facilitam as operações

com containers: listas, conjuntos e dicionários.

"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

mple

s

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 h

abit

 : d

on't

modif

y lo

op v

aria

ble

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.

>>> L=[4,6,1,7]>>> L[4, 6, 1, 7]>>> min(L)1>>> max(L)7>>> sorted(L)[1, 4, 6, 7]>>> L.pop()7>>> L[4, 6, 1]>>> 2*L[4, 6, 1, 4, 6, 1]>>> L.sort()>>> L[1, 4, 6]

Python: Voltando aos Containers❖ Existe um vasto leque de funções que facilitam as operações

com containers: listas, conjuntos e dicionários.

"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 h

abit

 : d

on't

modif

y lo

op v

aria

ble

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.

>>> L[1, 4, 6]>>> L = L + [9,8,4]>>> L[1, 4, 6, 9, 8, 4]>>> L.remove(4)>>> L[1, 6, 9, 8, 4]

Python: Voltando aos Containers❖ Trabalhando com conjuntos e seus operadores matemáticos.

"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

mple

s

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 h

abit

 : d

on't

modif

y lo

op v

aria

ble

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.

>>> A = {1,2,3,4,5}>>> A{1, 2, 3, 4, 5}>>> B = {4,5,6,7,8,9}>>> B-A{8, 9, 6, 7}>>> A-B{1, 2, 3}>>> A^B{1, 2, 3, 6, 7, 8, 9}>>> A&B{4, 5}>>> A|B{1, 2, 3, 4, 5, 6, 7, 8, 9}>>> A<BFalse>>> A&B < ATrue

Python: Voltando aos Containers❖ Dicionários (HashMap do Java). Uma associação eficiente entre chaves

e valores. Por outro lado, um dicionário é uma extensão de um conjunto

>>> precos= {}>>> precos= {'cafe':55}>>> precos{'cafe': 55}>>> precos['nata']= 65>>> precos['cerveja']= 75>>> precos{'cerveja': 75, 'nata': 65, 'cafe': 55}>>> precos['nata']= precos['nata'] + 2>>> precos{'cerveja': 75, 'nata': 67, 'cafe': 55}>>> precos.keys()dict_keys(['cerveja', 'nata', 'cafe'])>>> precos.values()dict_values([75, 67, 55])>>>

"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

mple

s

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 h

abit

 : d

on't

modif

y lo

op v

aria

ble

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.

Python: Voltando aos Containers❖ Dicionários (HashMap do Java). Uma associação eficiente entre chaves

e valores. Por outro lado, um dicionário é uma extensão de um conjunto

>>> precos{'cerveja': 75, 'nata': 67, 'cafe': 55}>>> for p in precos.keys():... print("O preço da", p, "é", precos[p])... O preço da cerveja é 75O preço da nata é 67O preço da cafe é 55>>>

"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 h

abit

 : d

on't

modif

y lo

op v

aria

ble

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.

Python: Manipular Strings❖ Para Strings dispomos

de um vasto repositório de funcionalidades prontas a serem aplicadas.

>>> s = "universidade da beira interior">>> s.islower()True>>> len(s)30>>> s.capitalize()'Universidade da beira interior'>>> s.title()'Universidade Da Beira Interior'>>>

Python: Manipular Strings❖ Para Strings dispomos

de um vasto repositório de funcionalidades prontas a serem aplicadas.

>>> s.ljust(40)'universidade da beira interior '>>> s.ljust(40,'.')'universidade da beira interior..........'>>> s.center(40,'.')'.....universidade da beira interior.....’>>> s.split()['universidade', 'da', 'beira', 'interior']>>> s.split('a')['universid', 'de d', ' beir', ' interior']>>> s.split('er')['univ', 'sidade da beira int', 'ior']>>>

Python: Manipular Strings❖ Exercício/exemplo:

Python: Manipular Strings❖ Exercício/exemplo:

bebidas= 'cerveja:75 cafe:50 agua:60 sumo:70'print('INPUT: ', bebidas)

print('OUTPUT:')print(''.ljust(30,'='))print('TABELA DE PREÇOS')print(''.ljust(30,'-'))

for b in bebidas.split() : np= b.split(':')print(np[0].ljust(20,'.'), np[1])

Python: Manipular Ficheiros❖ Interessam-nos essencialmente ficheiros de texto.

Python: Manipular Ficheiros❖ Interessam-nos essencialmente ficheiros de texto.

ficheiro = open('Uber.txt', 'r', encoding='utf8')linhasTexto= ficheiro.readlines()ficheiro.close()

for linha in linhasTexto :print('#', linha)

ficheiro = open('Uber.txt', 'r', encoding='utf8')

while True :linha= ficheiro.readline()if not linha : breakprint('##', linha)

ficheiro.close()

Versão A

Versão B

Python: Manipular Ficheiros❖ Interessam-nos essencialmente ficheiros de texto.

ficheiro = open('Uber.txt', 'r', encoding='utf8')while True :

linha= ficheiro.readline()if not linha : breakprint('##', linha)

ficheiro.close()

Versão C

Versão B

with open('Uber.txt', 'r', encoding='utf8') as ficheiro :for linha in ficheiro :

print('###', linha)

Versão mais moderna e também a mais utilizada!

Quais as vantagens?

Python: Manipular Ficheiros❖ Escrita em ficheiros. Exemplo: queremos gerar um ficheiro com

N números aleatórios, gerados entre 0 e 99. Em cada linha devem ser escritos 10 números, separados por três espaços. Os números devem ficar alinhados à direita.

51 98 6 31 22 79 46 92 70 79 26 72 82 50 82 97 0 33 49 4 12 74 69 37 38 65 4 60 4 74 10 66 98 53 96 72 61 42 53 68 51 99 97 41 57 83 65 63 11 37 72 38 25 45 28 85 66 58 22 65 40 42 88 73 32 80 22 58 72 36 27 53 58 60 16 20 26 71 9 44 89 78 57 42 0 7 75 29 36 97 34 75 69 23 0 17 77 89 10 35

Python: Manipular Ficheiros❖ Escrita em ficheiros. Exemplo: queremos gerar um ficheiro com

N números aleatórios, gerados entre 0 e 99. Em cada linha devem ser escritos 10 números, separados por três espaços. Os números devem ficar alinhados à direita.

import random as ran

print('PROGRAMA PARA ESCREVER N NÚMEROS ALEATÓRIOS NUM FICHEIRO')N= int(input('N=? '))

with open('Aleatorios.txt', 'w') as ficheiro :for n in range(1,N+1) :

x= ran.randint(0,99)ficheiro.write(str(x).rjust(4))if n % 10 == 0 :

ficheiro.write('\n')

Python: Definição e uso de Funções

Python: Definição e uso de Funçõesimport random as ran

def geradorAleatorios(fnome='Aleatorios.txt', N=100):with open(fnome, 'w') as ficheiro :

for n in range(1,N+1) :x= ran.randint(0,99)ficheiro.write(str(x).rjust(4))if n % 10 == 0 :

ficheiro.write('\n')

if __name__ == '__main__':print('GERADOR DE N NÚMEROS ALEATÓRIOS')nome= input('Nome do ficheiro: ')try:

N= int(input('N=? '))except Exception:

N= 100

if len(nome) > 0 :geradorAleatorios(nome,N)

else:geradorAleatorios(N=N)

Python: Tratamento de Código Crítico❖ Como podemos tratar blocos de instruções críticas?

❖ Exemplo:

try:x = int(input('Introduza um número inteiro: '))

except Exception as e:print('Erro: isso não é um inteiro :(')quit()

Exercício em Python

Crie um programa em Python que abre um ficheiro de texto e gera uma lista de todas as palavras únicas que lá ocorrem (vocabulário do ficheiro) e as respetivas frequências (número de vezes que ocorre) de cada palavra.