0 ratings0% found this document useful (0 votes) 43 views2 pagesCheat Sheet
The basics of python language
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
(©2012-2015 Laaren Poi Ment 9206 Python 3 Cheat Shoot tam wren
ie Csie Comme Avte
Cateelmee totnin cco nema
inter, flo, boolean sing, Bytes
int 783 0-192 gb010 00642 OxF3 Wet 18.9) Gee Cer t
float 9.23°0;0 -1.106 tuple (18,9) tty 7 6 (me 6
jose ip tleg ty et Na nhl ve oman) reese state
SE *one\aTwo" —Ahhine SOLE BYtO rdeed myn r/o :
nga be semme Tes. 1 hey containers print onde, fast Rey ens. em Rey wre
Tym 1e2\83""" | aut dct (hey" val
expel * pend || hrvtonranetorey (1: one 3
bytes b"teto\xi e\ 775"
headatoal ead —
mn nypetapeana)
Ant ("3£", 16) + 63 ‘can specify imeger mumber base wn I~ parameter
int (15.56) + 15 truncate decimal part
float ("-11.24e8") -+ -1124000000.0
round (15.56, 1)-+15.6 rounding 1o | decimal (0 decimal -+ integer number)
bool (x) False for null x, empty container x , None Of False i ; True for other #
‘Ste (x)—+"—" representation string of x for display (of forming om the baw)
chr (64)9'@' ord ('@') +64 code #+ char
repr (x)-+ "." literal representation string of x
bytes({72, 9, 64}) —» b'm\te’
List ("abe") + [
dict ([(3,"three"), (1,"one")}) + (1:'one’,3:'three')
set ({*one", "two"]} + (‘one', ‘two')
‘separator 8 and sequence of Bt -+ assembled 8tE
':* join(['tote', '12', ‘pawd'}) + "toto: 12:pewd’
ste splited on whiespaces“» List of et
“words with spaces". split() -+ ['words', ‘with’, ‘spaces')
‘str splined on separator str — List of str
"1,4,8,2".split(",") + ['1', ay
sequence of one type -* 1L4.st of another type (via list comprehension)
[Ant (x) for x in (11', 129", '=3")) + (1,29,-3)
Tris ola be Cin)
‘meses, clases. names
a2A_2_folloned by a_2A.2_0.9
© diacritics allowed but should be avoided
© language keywords forbidden
© lower/UPPER case discrimination
@ a tote x7 ymax Bigone
0 by end dow
{assignment c binding of name with value
1 evaluaon of righ sd expresion value
2) asigrmen order wih ef de names
x=1.2+8+8in (y)
asb=c=0 asigunen w same vale
¥, 2, F=9.2,-7.6, 0 mulpieasignmens
sue dex aToraia ems count Individual acces wo Hem via Lt (out)
pseinda 0 1 2 3 4 | en(Lst)o5 1st [0]110 pmae et [1] #20
Ast=[10, 20, 30, 40, 50) |, Mat E1150 wie Lat (=a
puimetee 9 2 2 2 4 8 (On mule sequences (14.8), remove with
namie 5 A 3 2 OD (ere frm 0104) ak Lat (3 and mony with assignment
‘Access to sub-sequences via Let [stam slic: end sce: ep) MAIS
Ast [:-1]=[10,20, 30,40] Lst[::-1]+{50,40,30,20, 10] 1st {1:3]+{20,30) 1#t{:3}+{10, 20, 30)
Ast [1:-1]+[20, 30,40] 1st{::-2]+(50, 30,10) Lat (-3:-1]=130, 40) 16t[3:}+[40, 50)
Ast [::2]+[10,30,50] 1st [:]+[10,20, 30, 40, 50) satow cy of ene
Missing sce indication ~ from sat /up end.
(On male sequences (14st), remove wih deh 1st {3:51 and modify wih assignment Lat (1:4) *115, 251
Cane
Comparisons :< > <= 3=
(Geviean resis)” SE
@ and. logical and oth sts.
one or other
a oF DB logicalor mays
{ pall: and and ox ream ae of oF
of (ander short evasion)
‘S exave hat and ae booleans
not a logical not
Amport monmod Sarre is monaod. nom!
{motes and packages searched i pen pth cf ypc)
Vacmdiion iste
4£ logical condition: Gebs
— | statements block
Can go with sever ef if. ad nly one
final eve Only the block of fist ue 58 expen
staeee
condition executes allen
ith var stater"hat bees
LE boot (a)eetrve: eo ata: ele
Lf bool(a)esFalee:e if not x: States Active
empire edtorw inser 4 spaces
lace of an aden th
from math import sin, pi
sin (pi/4) 0.707.
cos (2*pi/3)~-0.4999..
matic x pte Sonar sqrt(8i)-9.0. 7
(145.39 #2012.6 log (e**2)+2.0 Errors processing at
abs (23.2) 23.2 ceil (12.5)13 ery!
round (3.57, 1)3.6 floor (12.5)=12 normal processing block
Pow (4, 3}=64.0 mods ath, statistics, random |} except Fein 88 @: 4 euntity hit he fad pec
‘ual order of operations _dacinal, fractions, numpy. dc. die) error processing Mock al es
Scanned with CamScannerwatenens Hock ecwed orton os COIOETD
conto
while logical condition: fe
—inatements block GAT”
8 = 2} initatisanions before the ho
tog _cundinom with a least one varwable value (here 4),
100
ota
4.1” tmake condom variable change!
print ("sum") 8) for
Tee het
print ("v=",3,"em :",x,",", ya)
items to display : literal values, variables, expressions
Print options:
Saepa” ” items separator, default space
cend="\n" ‘end of print, default new line
© filessys.stdout print to file, defauk standard out
s = input ("Instructions:") [out |
# input alvays reums a string, conver it 1 required type
(¢f. bored Conversions on the other side),
‘Len (¢)— items count
min (ec) max(c) sum(e) "Nae: For dctonanes and set, these
sorted (c)—+ 11st sorted copy operations use hey.
val in c- boolean, membership operator in (absence not in)
‘enumerate (c) > iteraor on (index, vale)
Ap (C1, c2.-)-» erator on tuples containing €, tems at same index
811 (c) + True if all c items evaluated to ue, else Fas:
any (c)—+ True if at least one item of ¢ evaluated true, ese Fa
‘Specie wo ordered sequences containers (ss ples, sings Bex.)
Feversed(c) + imered ieator c*5-+ duplicate +02 concatenate
index (val) — posiion 5..count (val) event cout
import copy
‘copy . copy (6) ~ shallow copy of container
copy. deepcopy (<)> deep copy of container
‘4 mosity original st [ Operations on Lists ]
Ast.append(val) add item atend
Let rextend(sey) add sequence of items at end
Let insert (ide, ml) inser item at index
Ast remove val) remove fst item with valve val
Ast pop ([ids]) —+value remove & rerun item at index ls (default st)
Ast sort () 1st.reverse() sort/ reverse liste in place
Afkey} =value ‘d.clear() ela
lUizy)=> wae dad dftey] || | = min (une ere)
d.update (d2) {| = * =v diferencefsymmetric diff
lackeyet) i < pe = inchan relations
Jd. values () [ erable views on Operavors also exist as methods.
Ja. Yeens() ) towsoheshssciatons
update (:2),.copy ()
add (ta) s.remove (key)
‘discard(t) #.clear()
Pep ()
'd.pop (Keyf.defauli)) - value
}d-popitem ()— (key.value)
'd.get (hey/.defauli)) > value
a. setdetault (tof def) value
org data on ds, and reading back @
f = open("file.txt", "w",encoding= "ute
luton clem gethee came
eee ee ee See
roy re tee
path and pathtibs tt
‘tread empty sring if end of fle reading
f.read({n)) next chars
if non specie, read upto end!
E.readLines (/n)) ~ 11st of netines
fireadline() nadine
tet mode t by def (readAerite at) possible binary
rode ® (readfurie bytes). Convert from required type!
E.close() $n forge to dose the file after use!
Sat tht ret Latin!
£.write("coucou")
f writelines (lis of ines)
ak dmmehae eut
continue nett eration
TENT OIOTE ere tong sistorent |
fem of nbs ower ‘
for var in wyene +
4 statemente Blow m)
Ci eret sequence + vahoes
48 home
mot '
’
pint (Hounds, ent i
gon set ohn tye meee
asker hep ot teen oe
Go over sequence's index Z
modiy tem a inden 3
acest ter arn inex (before afer)
23,417) j
or ange (ies th A bt en rer
{OP kde he eacpeiestteenys A
a &§
ont heat)
| Go simultaneously over sequence s index and vahoes
for idx,val in enumerate (ist) :
ange (star | end [.step!) x
fut deta 0, rad net chided a sequence, orp ened. dete |
ange (3)-»01234 range (2
range (3,0)-+34367 range (2
ange (Len (ey) ) + sequence of inde of wet sy
range provides a train ween of Ws comida Redd
on iiees! rr
named parameters
det fot (x,y, 2): [ee]
‘documentation"**
4 statements block, res computation, ec.
return res reuk wlve of te call, f no campus
reat ireura return Hone
parameters anda
‘vanabls ofthis lock exist only the Block and dur the function
call (dua of “black Box)
Advanced: dof fet (x,y, 8, *arge, and,bes, *ekwarge) :
‘ares variable psionl apumens (-+ Cup La, defi vies
‘hwarysvoriale named arguments (dict)
rs £9553, i¢2,2*1) [ Function Call |
storagenase of one argument per
arsedvoe ——porameer
fie de wed hncion Advanced
tuck doe bec “en
upper() s-lower() s.title() s.seapesse()
‘canefold() " s.capitalize() — #.center (/wsth Ail)
gust (wish fll) @.eyust width fill) 8. efhLL Unt
encode (encadng)
——
Smodele() () ()*.format (x,y, 2)—+ ste
{selection formatting conversion )®
= Sakon format (43.72799)
E.flush() wicahe £. truncate (/sce)) ne
reat regal ee moe a 2000 sme Oman trite wit
Eel pon ek pesto) _____ rot cr trl a a 8
connor pening witha Fare with open 7] fot «ore exgecntal oF fue pn go 6 aprorate (Stak,
{asomai cn) and reading oop ones for line inf: |i oamgeone - nan
of ate fle E processing f tne _)\ 2 Canerson: wrens or€ Qr eprsne)
Scanned with CamScanner