Python 3 Cheatsheet
Python 3 Cheatsheet
Python 3 cheatsheet
f
orvari
abl
es
,fun
cti
ons
, Identifiers 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 lrepresentation 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 equen c
eo 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
-5 -4 -3 -2 -1 (here from 0 to 4)
n
egat
iv
esl
i
ce 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]→[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]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
emov hdel lst[3:5]a
ewi
t ndmo
dif
ywi
t
has
si
gnme
ntlst[1:4]=[15,25]
-
neo
usl
y ⁝ ☝ modules and packages searched in p
yth
onp
ath(cf sys.path)
a or b logical or oneorot
her p
arent
stat
emen:
t 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 htaa
a ndbareboo
leans
. no
not a logical not
n
ext
sta
teme
nta
fte
rbl
ock1 s
tat
ement
sbl
ock
True ☝config
uree
dit
ort
oinse
rt4sp
ace
sin
Can go with several el i
f,el
if... and only one
True and False constants final e
ls if age<=18:
. Only the block of first true
e
False 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"
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 × pyt
hon3.
5+numpy sqrt(81)→9.0 √ raise Ex c Cl
ass(
…) err
or
(1+5.3)*2→12.6 log(e**2)→2.0 Errors processing: n
orma
l proc
ess
ing
abs(-3.2)→3.2 ceil(12.5)→13 try: raiseX(
) e
rro
rraise
p
roc
ess
ing p
roce
ssi
ng
round(3.57,1)→3.6 floor(12.5)→12 nor ma lproc esi
si
ngblo
ck
pow(4,3)→64.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.
!
s s
tat
ement
sbl
ockex
ecu
tedasl
ongas Conditional Loop Statement s
tat
ement
sbl
ockexe
cut
edfo
re h Iterative Loop Statement
ac
c
ondit
i
onist
rue i
t
emo facon
tai
nerori
te
rat
or
op
next
o
yes
while l
ogi
calco
ndit
i
on: for var in s
eque
nc:
e
el
? Loop Control …
t
finish
fini
no
s
tat
ement
sblo
ck break i
mmediat
eexi
t st
at
emen
tsb
loc
k
continue n
exti
ter
ati
on
fin
s=0 i
ni
ti
al
iz
ati
onsbe
for
ethel
oop ☝ elseblo
ckf
orno
rmal Go over sequence's values
eo
i=1 c loopex
it
. s = "Some text" i ni
ti
ali
za t
i
onsbe
for
etheloop
r
ondi
ti
onwithal
east
oneva
ria
blev
alu
e(h
erei)
wa
Al
go: cnt = 0
s = s + i**2
i=i+1 ☝ ma
kec
ondi
t
ionv
ari
abl
ech
ang
e! s= ∑ i 2 for c in s:
if c == "e": Algo:c
o u
nt
print("sum:",s) i=1 cnt = cnt + 1 numb e
rofe
print("found",cnt,"'e'") inth
es t
ri
ng.
print("v=",3,"cm :",x,",",y+4) Display loop on dict/set ⇔ loop on keys sequences
use sl
icesto loop on a subset of a sequence