Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

©2012-2015 - Laurent Pointal Mémento v2.0.

6
License Creative Commons Attribution 4 Python 3 Cheat Sheet La
ht
t
p
t
e
s
s
t
:
/
v
/
p
e
e
r
s
r
s
i
o
o
no
.
li
n:
msi
.
fr/
poi
nt
al
/p
yth
on:
meme
nto
i
nt
ege
r,flo
at,b
ool
ean
,st
ri
ng,b
yte
s Base Types ◾ ordered sequences, fast index access, repeatable values Container Types
int783 0 -192 0b010 0o642 0xF3 list [1,5,9] ["x",11,8.9] ["mot"] []
z
ero b
ina
ry o
cta
l h
exa tuple (1,5,9) 11,"y",7.4 ("mot",) ()
float9.23 0.0 -1.7e-6
-6 No
nmo
difia
blev
alu
es(
immu
tabl
es) ☝e xp
ress
ionwit
hon
lycoma
s"tuple
boolTrue False ×10
""
str bytes ( o
rdere
dse
que
ncesofcha
rs/b
yte
s)
str"One\nTwo" Mu lti l
i
nes
tr
ing
: b""
e
sca
pedn
ewl
i
ne """X\tY\tZ ◾ key containers, no ap
rio
riorder, fast key access, each key is unique
'I\'m' 1\t2\t3""" dictionary dict {"key":"value"} dict(a=3,b=4,k="v") {}
e
sca
ped' e
sca
pedt
ab (
key
/va
luea
sso
cia
ti
ons
){1:"one",3:"three",2:"two",3.14:"2"}
bytesb"toto\xfe\775" collection set {"key1","key2"} {1,9,3,0} set()
h
exa
dec
ima
loc
tal ☝i
mmu
tab
les ☝k
eys
=ha
sha
blev
alu
es(
bas
ety
pes
,immu
tab
les
…) frozenseti
mmu
tab
les
et e
mpt
y

f
orvari
abl
es
,fun
cti
ons
, Identiers type(e xp
res si
on ) Conversions
modu
les
,cl
ass
es…names
int("15") → 15
int("3f",16) → 63 nd
can specify integer number base in 2 parameter
a…zA…Z_followed by a…zA…Z_0…9
◽ 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) Falsefor null x, empty container x, Noneor Falsex ; Truefor other x
⇥ 8y and for str(x)→ "…" representation string of xfor display ( cf.f orma tt
in gont
heb a
ck)
chr(64)→'@' ord('@')→64 code ↔ char
= Variables assignment
repr(x)→ "…" l it
er
a l
 representation string of x
☝ assignment ⇔ binding of a namewith a v
alu
e
1)e va l
uati
onofr i
ghtsideex pre
ssio
nva l
u e bytes([72,9,64]) → b'H\t@'
2)a ssignmenti
no rderwithl eft
sidena
me s list("abc") → ['a','b','c']
x=1.2+8+sin(y) dict([(3,"three"),(1,"one")]) → {1:'one',3:'three'}
a=b=c=0 as s
ignme ntt
osamev a
lue set(["one","two"]) → {'one','two'}
y,z,r=9.2,-7.6,0 mul t
ipl
eass
ign
ments separat
orstrand s equenceo fstr→ a ssemb ledstr
a,b=b,a valu esswap ':'.join(['toto','12','pswd']) → 'toto:12:pswd'
a,*b=seq unpacki ngofseq
uencei
n strs plit
tedo nwh it
espaces→ listof str
*a,b=seq i tema n
dl i
st "words with spaces".split() → ['words','with','spaces']
and strs plit
tedo ns eparatorstr→ listo fstr
x+=3 i ncre
me nt% x=x+3 *=
x-=2 decr eme nt% x=x-2 /= "1,4,8,2".split(",") → ['1','4','8','2']
x=None «undefin
e d»const
antval
ue %= sequence of one type → listof another type ( vi
al istcomp rehe nsion )
del x r
emo
ven
amex … [int(x) for x in ('1','29','-3')] → [1,29,-3]
f
orl
i
sts
,tu
ples
,st
ri
ngs
,by
te s
… Sequence Containers Indexing
n
egat
iv
ein
dex -5 -4 -3 -2 -1 Items count Individual access to items via lst[i
nde
x]
pos
it
iv
einde
x 0 1 2 3 4 len(lst)→5 lst[0]→10 - fir
stone lst[1]→20
lst=[10, 20, 30, 40, 50] lst[-1]→50 -l asto
ne lst[-2]→40
pos
it
iv
esl
ic
e 0 1 2 3 4 5 ☝ index from 0
Onmutab
les
equ
ence
s(list)
,re
movewit
h
n
egat
iv
esl
i
ce -5 -4 -3 -2 -1 (here from 0 to 4)
del lst[3]andmodi
fywi
thass
ign
ment
lst[4]=25
Access to sub-sequences via lst[s
tar
tsl
i
ce:e
nds
li
ce:s
te
p]
lst[:-1]C[10,20,30,40] lst[::-1]C[50,40,30,20,10] lst[1:3]C[20,30] lst[:3]C[10,20,30]
lst[1:-1]C[20,30,40] lst[::-2]C[50,30,10] lst[-3:-1]C[30,40] lst[3:]C[40,50]
lst[::2]C[10,30,50] lst[:]C[10,20,30,40,50]sh
all
owco
pyofs
equ
enc
e
Mis
si
ngsl
icei
ndi
cat
ion" fr
oms t
art
/upt
oen
d.
Onmuta
blese
quenc
es(list),r
emovewi
t
hdel lst[3:5]a
ndmo
dif
ywi
t
has
si
gnme
ntlst[1:4]=[15,25]

Boolean Logic Statements Blocks mo


dul
etruc%fil
etruc.py Modules/Names Imports
Comparisons : < > <= >= == != from monmod import nom1,nom2 as fct
(b
ool
eanresul
ts) ⌅ ⇤ = p
are
ntst
atement
: "di
re
cta
cce
sst
ona
mes
,re
nami
ngwi
t
has
a and b logical and b
oths
imu
lt
a- s
tat
ementbl
ock1… import monmod"ac
ces
svi
amonmod.nom1…
indentation !

-
neo
usl
y H ☝ modules and packages searched in p
yth
onp
ath(cf sys.path)
a or b logical or oneorot
her p
arent
stat
ement
: s
tat
ement
blo
ckexec
ute
don
ly
orb o
th Conditional Statement
s
tat
ementbl
ock2… i
fac o
ndi
ti
onist
rue
☝ pitfall : anda ndorre
tur
nv al
ueofao
r ⌅ yes no yes
ofb( un de rsho
rtc
ute
val
uat
ion)
. if l
ogi
calc
ondi
ti
on: ? ?
-e n su ret ha
taa ndbareboo
leans
. no
not a logical not
n
ext
sta
teme
nta
fte
rbl
ock1 s
tat
ement
sbl
ock
True Can go with several el i
f,el
if... and only one
True and False constants ☝config
uree
dit
ort
oinse
rt4sp
ace
sin if age<=18:
False 8nal else
. Only the block of 8rst true
pl
aceo fani
ndent
at
io
ntab. state="Kid"
condition is executed. elif age>65:
☝ flo
ati
ngn
umb
ers
…ap
pro
xima
tedv
alu
es a
ngl
esi
nra
dia
ns Maths ☝ wi
t
havarx: state="Retired"
if bool(x)==True: ⇔ if x: else:
Operators: + - * / // % ** from math import sin,pi… state="Active"
if bool(x)==False:⇔ if not x:
Priority (…) × ÷ ab sin(pi/4)C0.707…
integer ÷ ÷ remainder cos(2*pi/3)C-0.4999… Exceptions on Errors
Signaling an error:
@→ matrix × pyt
hon3.
5+numpy sqrt(81)C9.0 N raise Ex c Cl
ass(
…) err
or
(1+5.3)*2C12.6 log(e**2)C2.0 Errors processing: n
orma
l proc
ess
ing
abs(-3.2)C3.2 ceil(12.5)C13 try: raiseX(
) e
rro
rraise
p
roc
ess
ing p
roce
ssi
ng
round(3.57,1)C3.6 floor(12.5)C12 nor ma lproc esi
si
ngblo
ck
pow(4,3)C64.0 modules math, statistics, random, except Ex c
ep t
i on as e: ☝ finallybl
ockf
orfin
alp
roc
ess
ing
☝usu alo rdero fop er
ati
ons decimal, fractions, numpy, etc.(c
f.do
c) errorp roces si
ngblo
ck inallc
ase
s.

You might also like