Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Python 3 Cheatsheet

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Python 3 Cheatsheet

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

lOMoARcPSD|46630154

Python 3 cheatsheet

python programming (Lovely Professional University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Harsha vardhan Poluri (poluriharshavardhan210@gmail.com)
lOMoARcPSD|46630154

©2012-2015 - Laurent Pointal Mémento v2.0.6 Lat


es
tver
si
onon:
License Creative Commons Attribution 4 Python 3 Cheat Sheet ht
t
ps:
//
per
so.
li
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
No
nmo
difia
blev
alu
es(
immu
tabl
es) ☝e xp
ress
ionwit
hon
lycoma
s→tuple
boolTrue False ×10
-6
""
str bytes ( o
rdere
dse
que
ncesofcha
rs/b
yte
s)
str"One\nTwo" Mu lt
i 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
on){1:"one",3:"three",2:"two",3.14:"π"}
s
bytesb"toto\xfe\775" collection set {"key1","key2"} {1,9,3,0} set()
h
exa
dec
ima
loc
tal ☝i
mmu
tab
les ☝k
ey=h
s a
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
, 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]

Boolean Logic Statements Blocks mo


duetruc⇔fil
l etruc.py Modules/Names Imports
Comparisons : < > <= >= == != from monmod import nom1,nom2 as fct
(b
ool
eanresul
ts) ≤ ≥ = ≠ p
are
ntst
atemen:
t →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 ⁝ ☝ 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.

Downloaded by Harsha vardhan Poluri (poluriharshavardhan210@gmail.com)


lOMoARcPSD|46630154

!
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

☝ good habit : don't modify loop variable


while i <= 100: i=100 l
o opva ri
ab l
e,as si
g nme ntmanag e
dbyfors t
atement
e
☝b

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

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


printoptions: ◽ 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 file, default standard output for idx in range(len(lst)): Alg
o:l
imi
tval
uesgr
eat
er
val = lst[idx] t
han15,memori
zi
ng
s = input("Instructions:") Input
if val > 15: ofl
ost
valu
es.
☝ inputalways returns a string, convert it to required type lost.append(val)
(cf. boxed Co
nversi
on son the other side). lst[idx] = 15
print("modif:",lst,"-lost:",lost)
len(c)→ items count Generic Operations on Containers Go simultaneously over sequence's index and values:
min(c) max(c) sum(c) No te:Fordi c
ti
on ari
esan
dse
ts
,th
ese for idx,val in enumerate(lst):
sorted(c)→ listsorted c o py op erat
ionsu eke
s ys.
val in c→ boolean, membership operator in(absence not in) range([ star t
,]e n d[ ,
step ]) Integer Sequences
enumerate(c)→ i teratron (index, value)
o ☝st
ardefault 0, e
t n dnot included in sequence, s
tpsigned, default 1
e
zip(c1,c2…)→ i t
er
a tron tuples containing ci items at same index
o
range(5)→ 0 1 2 3 4 range(2,12,3)→ 2 5 8 11
all(c)→ Trueif all citems evaluated to true, else False range(3,8)→ 3 4 5 6 7 range(20,5,-5)→ 20 15 10
any(c)→ Trueif at least one item of cevaluated true, else False range(len(s eq))→ s equenceo fi ndexofv alu
esinseq
S
pec
i oo
fict r
der
eds
eque
nce
sco
nta
ine
rs(
li
st
s,t
upl
es
,st
ri
ngs
,by
tes
…) ☝r
ang
epr
ovi
desa
nimmu
tab
les
equ
enc
eofi
ntc
ons
tr
uct
eda
sne
ede
d
reversed(c)→ in
vers
edit
er
atr c*5→ duplicate
o c+c2→ concatenate
c.index(va)→ pos
l i
t
ion c.count(v al )→ e
vent
sco
unt function name (identifier) Function Definition
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 #st
at
ement
sbl
ock,r
esc o mp u tatio n,e tc .
lst.append(va)
l add item at end return res result value of the call, if no computed
result to return: return None
lst.extend(se
q) add sequence of items at end ☝ parameters and all
lst.insert(i
dx,va) insert item at index
l variables of this block exist only inthe block and du r
ingthe function
lst.remove(va)
l remove first item with value v al call (think of a “black box” )
lst.pop([i
dx)→v
] a
lue remove & return item at index i
dx(default last) Advanced: def fct(x,y,z,*args,a=3,b=5,**kwargs):
lst.sort() lst.reverse() sort / reverse liste i nplace *a r gsvariab lepo si
ti
o nala r
gume nt
s( →tuple) ,de
faultva l
ues,
**k wa r
g sva riablen ame da r
gu me n t
s( →dict)
Operations on Dictionaries Operations on Sets
d[ke
y]=value d.clear() Operators: r = fct(3,i+2,2*i) Function Call
| → union (vertical bar char) s
tor
age
/us
eof o
nearg
ument
per
d[ke
y]→ value del d[k ey] & → intersection r
et
urne
dvalu
e p
ara
meter
d.update(d2) update/add - ^ → difference/symmetric diff. ☝ this is the use of function fct() fct
associations Advanc
ed:
d.keys() < <= > >= → inclusion relations name wi thp arenthe se
s *se
quenc
e
d.values() →i t
erablev iewso n Operatorsa l
soexis
t asme th ods. which does the call **di
ct
d.items() k eys/
values/a s
so c
iat
i
ons
d.pop(key[
,defa
u l
t])→ v a l
u e s.update(s2) s.copy()
s.add(ke
y) s.remove(key) s.startswith(p r
efix[,
st
art
[,e
n d]
]) Operations on Strings
d.popitem()→ ( key,
v alu e)
d.get(key[
,defa
u l
t])→ v a l
u e s.discard(ke) s.clear()
y s.endswith(suffix
[,star
t[,
end]) s.strip([
] c
hars)
]
d.setdefault(k
ey[
,de
fau
lt
])→v
alu
e s.pop() s.count(sub
[,s
tar t
[,
e nd]) s.partition(s
] ep)→ (bef
ore,
se
p,after)
s.index(sub
[,s
tar t
[,
e nd]) s.find(s
] ub[
,star
t[,
end])
]
s
tor
ingda
tao
ndi
sk,a
ndr
eadi
ngi
tba
ck Files s.is…() t
est
sonc h
ar scat
egori
es(e
x.s.isalpha())
f = open("file.txt","w",encoding="utf8") s.upper() s.lower() s.title() s.swapcase()
s.casefold() s.capitalize() s.center([ wi
dth,fil
l])
file variable name of file
opening mode encoding of s.ljust([wi
dth,fil
l) s.rjust([
] widt
h,fil
l) s.zfill([
] width])
for operations on disk ◽ 'r'read chars for t
ext s.encode(encoding) s.split([ se
p]) s.join(s e
q)
(+path…) ◽ 'w'write fil
es:
◽ 'a'append utf8 ascii formating directives values to format Formatting
cf. modules os, os.pathand pathlib◽ …'+' 'x' 'b' 't' latin1 …
"modele{} {} {}".format(x,y,r) str
writing ☝r
eade
mpt
yst
ri
ngi
fen
doffil
e reading "{se
lec
ti
on:f
orma
tt
in
g!con
ver
si
on}"
f.write("coucou") f.read([
n]) →n
ext
cha
rs
◽ Selection :
f.writelines(l
i
sto
fli
ne)
s i
fnn ot sp eci
fied,r eadu ptoend! "{:+2.3f}".format(45.72793)
2
Examples

f.readlines([ n] ) → listo fne


xtl
i
nes →'+45.728'
f.readline() →n e
x t
li
ne nom "{1:>10s}".format(8,"toto")
☝te
xtmodetb yde fault(rea d/writestr) ,p ossibl
eb i
nar
y 0.nom →' toto'
4[key] "{x!r}".format(x="I'm")
modeb( read/wr i
tebytes) .Co n vertf rom/ tor equi r
edtype! 0[2]
f.close() ☝ dont forget to close the file after use ! →'"I\'m"'
◽ Formatting :
f.flush()write cache f.truncate([ size ) resize
] fil
lch ara lig n
men
tsi
gn mi
niwi
dt.p
h re
cis
ion~ma
xwi
dt
h type
re
adi
ng/
wri
t
ingpr
ogressseq u
e nti
a l
lyi nt hefile,mo difiablewi th:
<>^= +-s pac
e 0at start for filling with 0
f.tell()→p
osi
t
ion f.seek(p
osi
t
ion[
,or
igi
n]) integer: bbinary, cchar, ddecimal (default), ooctal, xor Xhexa…
Very common: opening with a guarded block with open(…) as f: float: eor Eexponential, for Ffixed point, gor Gappropriate (default),
(automatic closing) and reading loop on lines for line in f : string: s… %percent
of a text file: #p r
oces
si
ngo
fline ◽ Conversion : s(readable text) or r(literal representation)

Downloaded by Harsha vardhan Poluri (poluriharshavardhan210@gmail.com)

You might also like