Anda di halaman 1dari 2

2012-2015 - Laurent Pointal Mmento v2.0.

4
License Creative Commons Attribution 4
Python 3 Cheat Sheet Latest version on:
https://perso.limsi.fr/pointal/python:memento
integer, %oat, boolean, string, bytes Base Types ordered sequences, fast index access, repeatable values Container Types
int 783 0 -192 0b010 0o642 0xF3 list [1,5,9] ["x",11,8.9] ["mot"] []
null binary octal hexa tuple (1,5,9) 11,"y",7.4 ("mot",) ()
float 9.23 0.0 -1.7e-6
-6 Non modiable values (immutables) expression with just comas tuple
bool True False 10
""
str bytes (ordered sequences of chars / bytes)
str "One\nTwo" Multilinestring: b""
escaped new line """X\tY\tZ key containers, no a priori order, fast key acces, each key is unique
'I\'m' 1\t2\t3""" dictionary dict {"key":"value"} dict(a=3,b=4,k="v") {}
escaped ' escaped tab (key/value associations) {1:"one",3:"three",2:"two",3.14:""}
bytes b"toto\xfe\775" collection set {"key1","key2"} {1,9,3,0} set()
hexadecimal octal immutables keys=hashable values (base types, immutables) frozenset immutable set empty

for variables, functions, Identiers type(expression) Conversions


modules, classes names
int("15") 15
int("3f",16) 63 nd
can specify integer number base in 2 parameter
azAZ_ followed by azAZ_09
diacritics allowed but should be avoided int(15.56) 15 truncate decimal part
language keywords forbidden float("-11.24e8") -1124000000.0
lower/UPPER case discrimination round(15.56,1) 15.6 rounding to 1 decimal (0 decimal integer number)
a toto x7 y_max BigOne bool(x) False for null x, empty container x , None or False x; True for other x
8y and for str(x) "" representation string of x for display (cf. formating on the back)
chr(64)'@' ord('@')64 code char
= Variables assignment
repr(x) "" literalrepresentation string of x
1) evaluation of right side expression value
2) assignment in order with left side names bytes([72,9,64]) b'H\t@'
assignment binding of a name with a value list("abc") ['a','b','c']
x=1.2+8+sin(y) dict([(3,"three"),(1,"one")]) {1:'one',3:'three'}
a=b=c=0 assignment to same value set(["one","two"]) {'one','two'}
y,z,r=9.2,-7.6,0 multiple assignments separator str and sequence of str assembled str
a,b=b,a values swap ':'.join(['toto','12','pswd']) 'toto:12:pswd'
a,*b=seq unpacking of sequence in str splitted on whitespaces list of str
*a,b=seq item and list "words with spaces".split() ['words','with','spaces']
and str splitted on separator str list of str
x+=3 increment x=x+3 *=
x-=2 decrement x=x-2 /= "1,4,8,2".split(",") ['1','4','8','2']
x=None undened constant value %= sequence of one type list of another type (via comprehension list)
del x remove name x [int(x) for x in ('1','29','-3')] [1,29,-3]
for lists, tuples, strings, bytes Sequence Containers Indexing
negative index -5 -4 -3 -2 -1 Items count Individual access to items via lst[index]
positive index 0 1 2 3 4 len(lst)5 lst[0]10 rst one lst[1]20
lst=[10, 20, 30, 40, 50] lst[-1]50 last one lst[-2]40
positive slice 0 1 2 3 4 5 index from 0
On mutable sequences (list), remove with
negative slice -5 -4 -3 -2 -1 (here from 0 to 4)
del lst[3] and modify with assignment
lst[4]=25
Access to sub-sequences via lst[start slice:end slice:step]
lst[:-1][10,20,30,40] lst[::-1][50,40,30,20,10] lst[1:3][20,30] lst[:3][10,20,30]
lst[1:-1][20,30,40] lst[::-2][50,30,10] lst[-3:-1][30,40] lst[3:][40,50]
lst[::2][10,30,50] lst[:][10,20,30,40,50] shallow copy of sequence
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]

Boolean Logic Statements Blocks module trucle truc.pyModules/Names Imports


Comparators: < > <= >= == != from monmod import nom1,nom2 as fct
(boolean results) = parent statement: direct acces to names, renaming with as
a and b logical and both simulta-
statement block 1 import monmod acces via monmod.nom1
indentation!

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


a or b logical or one or other parent statement: statement block executed only
or both Conditional Statement
statement block2 if a condition is true
pitfall: and and or return value of a or yes no yes
of b (under shortcut evaluation). if logical condition: ? ?
ensure that a and b are booleans. no
not a logical not
next statement after block 1 statements block
True Can go with several elif, elif... and only one
True and False constants congure editor to insert 4 spaces in if age<=18:
False 8nal else. Only the block of 8rst true
place of an indentation tab. state="Kid"
condition is executed. elif age>65:
%oating numbers approximated values Maths
angles in radians with a var x: state="Retired"
if bool(x)==True: if x: else:
Operators: + - * / // % ** from math import sin,pi state="Active"
ab if bool(x)==False: if not x:
Priority () sin(pi/4)0.707
integer remainder cos(2*pi/3)-0.4999 Exceptions on Errors
Signaling an error:
@ matrix python3.5+numpy sqrt(81)9.0 raise Exception() Errors processing:
(1+5.3)*212.6 log(e**2)2.0 error try:
abs(-3.2)3.2 ceil(12.5)13 normal processing normal procesising block
raise error
round(3.57,1)3.6 floor(12.5)12 processing processing raise
except Exception as e:
pow(4,3)64.0 modules math, statistics, random, error processing block
usual priorities decimal, fractions, numpy, etc. (cf. doc) finally block for nal processing in all cases.
statements block executed as long as Conditional Loop Statement statements block executed for each Iterative Loop Statement
condition is true item of a container or iterator
beware of innite loops!

yes next
while logical condition: ? Loop Control for var in sequence:
no break immediate exit 8nish
statements block statements block
continue next iteration
s = 0 initializations before the loop else block for normal loop exit. Go over sequence's values
i = 1 condition with a least one variable value (here i) s = "Some text" initializations before the loop
Algo: cnt = 0

good habit: don't modify loop variable


while i <= 100: i=100 loop variable, assignment managed by for statement
s = s + i**2
i = i + 1 make condition variable change! s= i 2 for c in s:
if c == "e": Algo: count
print("sum:",s) i=1 cnt = cnt + 1 number of e
print("found",cnt,"'e'") in the string.
print("v=",3,"cm:",x,",",y+4) Display loop on dict/set loop on keys sequences
use slices to loop on a subset of a sequence

items to display: literal values, variables, expressions Go over sequence's index


print options: modify item at index
sep=" " items separator, default space access items around index (before / after)
lst = [11,18,9,12,23,4,17]
end="\n" end of print, default new line lost = []
file=sys.stdout print to 8le, default standard output for idx in range(len(lst)): Algo: limit values greater
val = lst[idx] than 15, memorizing
s = input("Instructions:") Input if val > 15: of lost values.
input always returns a string, convert it to required type lost.append(val)
(cf. boxed Conversions on the other side). lst[idx] = 15
print("modif:",lst,"-lost:",lost)
len(c) items count Generic Operations on Containers Go simultaneously on sequence's index and values:
min(c) max(c) sum(c) Note: For dictionaries and sets, these for idx,val in enumerate(lst):
sorted(c) list sorted copy operations use keys.
val in c boolean, membership operator in (absence not in) range([start,] end [,step]) Integers Sequences
enumerate(c) iterator on (index, value) start default 0, n not included in sequence, pas signed default 1
zip(c1,c2) iterator on tuples containing ci items at same index
range(5) 0 1 2 3 4 range(2,12,3) 2 5 8 11
all(c) True if all c items evaluated to true, else False range(3,8) 3 4 5 6 7 range(20,5,-5) 20 15 10
any(c) True if at least one item of c evaluated true, else False range(len(seq)) sequence of index of values in seq
Specic to ordered sequences containers (lists, tuples, strings, bytes) range provides an immutable sequence of int constructed as needed
reversed(c) inversed iterator c*5 duplicate c+c2 concatenate
c.index(val) position c.count(val) events count function name (identi8er) Function Denition
import copy named parameters
copy.copy(c) shallow copy of container def fct(x,y,z):
copy.deepcopy(c) deep copy of container fct
"""documentation"""
modify original list Operations on Lists # statements block, res computation, etc.
lst.append(val) add item at end return res result value of the call, if no computed
result to return: return None
lst.extend(seq) add sequence of items at end parameters and all
lst.insert(idx,val) insert item at index variables of this block exist only in the block and during the function
lst.remove(val) remove 8rst item with value val call (think of a black box)
lst.pop([idx])value remove & return item at index idx (default last) Advanced: def fct(x,y,z,*args,a=3,b=5,**kwargs):
lst.sort() lst.reverse() sort / reverse liste in place *args variable positional arguments (tuple), default values,
**kwargs variable named arguments (dict)
Operations on Dictionaries Operations on Sets
d[key]=value d.clear() Operators: r = fct(3,i+2,2*i) Function Call
d[key] value del d[key] | union (vertical bar char) storage/use of one argument per
& intersection returned value parameter
d.update(d2) update/add
associations - ^ diNrence/symetric diN. this is the use of function Advanced: fct() fct
d.keys()
< <= > >= inclusion relations
d.values() iterable views on name with parenthesis *sequence
Operators also exist as methods. which does the call **dict
d.items() keys/values/associations
d.pop(key[,default]) value s.update(s2) s.copy()
d.popitem() (key,value) s.add(key) s.remove(key) s.startswith(prex[,start[,end]]) Operations on Strings
d.get(key[,default]) value s.discard(key) s.clear() s.endswith(suBx[,start[,end]]) s.strip([chars])
d.setdefault(key[,default])value s.pop() s.count(sub[,start[,end]]) s.partition(sep) (before,sep,after)
s.index(sub[,start[,end]]) s.find(sub[,start[,end]])
storing data on disk, and reading it back Files s.is() tests on chars categories (ex. s.isalpha())
f = open("file.txt","w",encoding="utf8") s.upper() s.lower() s.title() s.swapcase()
s.casefold() s.capitalize() s.center([width,ll])
8le variable name of 8le
opening mode encoding of s.ljust([width,ll]) s.rjust([width,ll]) s.zfill([width])
for operations 'r' read
on disk chars for text s.encode(encoding) s.split([sep]) s.join(seq)
'w' write
(+path) les:
'a' append utf8 ascii formating directives values to format Formating
cf. modules os, os.path and pathlib '+' 'x' 'b' 't' latin1
"modele{} {} {}".format(x,y,r) str
writing read empty string if end of le reading "{selection:formating!conversion}"
f.write("coucou") f.read([n]) next chars
f.writelines(list of lines) if n not specied, read up to end! Selection : "{:+2.3f}".format(45.72793)
f.readlines([n]) list of next lines 2 '+45.728'
Examples

f.readline() next line nom "{1:>10s}".format(8,"toto")


text mode t by default (read/write str), possible binary 0.nom ' toto'
4[key] "{x!r}".format(x="I'm")
mode b (read/write bytes). Convert from/to required type! 0[2]
f.close() dont forget to close the le after use! '"I\'m"'
Formating :
f.flush() write cache f.truncate([taille]) resize ll char alignment sign mini width.precision~maxwidth type
reading/writing progress sequentially in the le, modiable with:
<>^= + - space 0 at start for 8lling with 0
f.tell()position f.seek(position[,origin]) integer: b binary, c char, d decimal (default), o octal, x or X hexa
Very common: opening with a guarded block with open() as f: Moat: e or E exponential, f or F 8xed point, g or G appropriate (default),
(automatic closing) and reading loop on lines for line in f: string: s % percent
of a text 8le: # processing ofline Conversion : s (readable texte) or r (literal representation)