Mémento v2.0.6 ©2012-2015 - Laurent Pointal License Creative Commons Attribution 4 (. . integer, float, boolean, string, bytes int 783 float str False True bytes diacritics allowed but should b e avoided o language keywords forbidden o lower/UPPER case discrimination y | x+=3 increment <> X = x + 3 x—=2 decrement <> X = x — 2 del IL remove name x ['a','b','c'] (1,"one")]) — {'one',l -5 positveindex 1 0 — list EN "1,4,8,2".split(",") || sequence of one type — l i s t [int 1 { 1st=[10, 9 positive slice negative slice ~~ —5 —2 -3 -4 2 i 20, 3 i 30; 1 2 —4 =3 (x) for x 1st[:-1]-[10,20,30,40] 1st[1:-1]-[20,30,40] 30,50] 1st[::2]-[10, 4 i | len in : 'spaces'] 'with', ['1','4','8','2"] ('1','29','-3"')] — [1,29,-3] Py Individual access to items via 1 s t [index] -5 1 s t [ 0 ] —=10 1st [-1]—>50 ? 3 (lst) ['words',6 — of str of another type (via list comprehension) Items count -1 i 40; 50] 4 -1 2 — {1l:'one',3:'three'} 'two'} spaces".split() with s t r splitted o n separator s t r — negative index e char cod« separator s t r and sequence o f s t r — assembled s t r '12', 'pswd']) — 'toto:12:pswd’ ':'.jJoin(['toto', s t r splitted on whitespaces — l i s t of s t r _ $= ; T r u e for other x X representation string of x for display (cf. formatting on the back) — "words and x=None «undefined » constant value x empty | Conversions F a l s e for null x , empty container x , N o n e o r F a l s e ("abc") list multiple assignments unpacking of sequence in | item and list set () f r o z e n s e t immutable set t y p e (expression) dict ([ (3, "three"), "two"]) set (["one", assignment to same value *a,b=seq {:} r e p r ( x ) — " . . " literal representation string o f x — b'H\tQ@' bytes ([72,9,64]) # assignment © binding of a name with a value 1) evaluation of right side expression value 2) assignment in order with left side names x=1.2+48+sin(y) a, *b=seq bm" : i chr (64)—>'QR' ord('Q@')—64 Variables assignment values swap i. order. fast k h kev oracr, ast Cy access, € a c Cy 1S unique — 15 ("15") str (x)— ".." 7 v,z2,r=9.2,-7.6,0 ori €y containers, no a priori bool (x) x 7 y_max BigOne a,b=b, a : 0 can specify integer number base in 2 " parameter ("3£f",16) — 63 int truncate decimal part int ( 1 5 . 5 6 ) — 1 5 float ("-11.24e8") — -1124000000.0 rounding to 1 decimal ( 0 decimal — integer number) round ( 1 5 . 5 6 , 1 ) — > 1 5 . 6 8 y and for a=b=c=0 [i] (ordered sequences of chars / bytes) bytes tai ["mot™] "mot", ( ) # expression with only comas —» t u p l e GALL Nall dict (a=3,b=4,k="v" {"key":"value"} dictionary d i c t (key/value associations) { 1 : " o n e " , 3 : " t h r e e " , 2 : " t w o " , 3 . 1 4 : " n " {1,9,3,0} {"keyl", "key2"} set collection Identifiers|f i n t o © a toto * str Container T y p e s ["x",11,8.9] 11, "y",7.4 g immutables | L # keys=hashable values (base types, immutables...) a..zA..Z_ followed by a...zA..Z_0...9 @ Oo nn "X\tY\t2Z hexadecimal octal ] ordered sequences, fast index access, repeatable values - k 1 \ t 2 \E3" n o escaped tab [ for variables, functions, modules, classes... names https://perso.limsi.fr/pointal/python:memento list [1,5,9] 1,5,9 _rtuple ( ) Non modifiable values (immutables) Multiline string: ' IN'm' escaped ' b"toto\xfe\775" L [wm x10 "One\nTwo" escaped n e w line Latest version o n : . ( CELERY L Y 0 -192 0b010 00642 OxF3 hexa binary octal zero 0.0 -1.7e—6 = 9.23 bool Python 3 Cheat Sheet 8 index from 0 (here from O to 4 ) = first one = lastone 1st [1]—20 1st [-2]—40 On mutable sequences ( 1 i s t ) , remove with d e l 1 s t [ 3 ] and modify with assignment 1st [4]=25 1st|[:: -1]-[50,40,30,20,10] 1st [1:3]-[20,30] 1st[:3]-[10,20,30] 1st|[:: -2]-[50,30,10] 1st[:]1-[10,20,30,40, lst [-3:-1]-[30,40] 1st[3:]-[40,50] 5 0 ] shallow copy of sequence Missing slice indication — from start / u p to end. On mutable sequences ( 1 i s t ) , remove with d e l Boolean L o g i c Comparisons : < > < = > = = = b and 2 < (boolean results) a logical = | # logical not | True and False constants True \_ ( 3 floating numbers... approximated values . Priority ( . . . ) @—- matrix % ** b X 4h a integer + + remainder X pyvthon3.5+numpy (145.3) *2-12.6 abs ( - 3 . 2 ) - » 3 . 2 round ( 3 . 5 7 , 1 ) - + 3 . 6 pow (4,3)-»64.0 9 8 usual order o f operations ; ... ) I Can go with several elif, elif... and only one final else. Only the block of first true sin (pi/4)-0.707.. cos (2*pi/3)->-0.4999.. vy sqrt ( 8 1 ) - + 9 . 0 log (e**2)->2.0 ceil (12.5)-13 (12.5)-»12 random, modules m a t h , s t a t i s t i c s , d e c i m a l , f r a c t i o n s , numpy, ec. (cf. doc) if \1f bool (x)==True: bool (x)==False: © © if if . (- Signaling an error: r a i s e ExcClass(...) Errors processing: try: — | normalprocesising block e x c e p t Exception a s e : \ error processing block —>| x: not 1 if age<=18: state="Kid" elif age>65: state="Retired" else: state="Active " # with a var x: sin, pi.. yes 10 statements block _/ | condition 1s executed. angles in radians f r o m m a t h import — | | FO : logica 1 condition if L place of an indentation tab. floor noml Conditional Statement (statement block executed only if a condition is true or # configure editor to insert 4 spaces in J —gccess via m o n m o d . \ # modules and packages searched i npythonpath (cf s y s . p a t h ) next statement after block 1 a monmod import oe = = // — direct access to names, renaming with a s 1. . R 2 paren 2 7 o f b (under shortcut evaluation). ensure that a a n d b are booleans. Operators: + — * / statement b l o c k . Sg = th of logicalor [ 5 7 b a or # pitfall : and and o x return value of a or False Modules/Names Imports (module trucefile t r u c . p y noml,nom2 a s fct f r o m monmod import parent statement : -neously not J Statements B l o c k s | a n d both simulta- . l s t [ 3 : 5 ] and modify with assignment 1 s t [ 1 : 4 ] = [ 1 5 , 2 5 ] 7 x: Exceptions o n Errors ¥ normal recone | — \J ¢ £ i n a l l y block for finalprocessing in all cases. J Conditional L o o p Statement statements block executed as long as 2 , condition is true . . S while S x <P "° | ——|statements block § = = Vd yes oe logical condition : Ny + = NY $ while i <= 1 0 NY s =s8s + 1 i=1i+1 Loop Control \. =u _— hi w® A A 1 sep=" " end="\n" o file=sys.stdout 0 Ss input lst = [11,18,9,12,23,4,17] = [] lost idx for if (cf. boxed Conversions o n the other side). val (c)— list in A. p r i n t Generic Operations o n Containers c — boolean, membership operator i n (absence n o t in) r a n g e ( l e n (seq) ) — sequence o f index o f values in seq d.keys (function name (identifier) named parameters def . Operations o n L i s t s 1 s t . append (val) add item at end l s t . e x t e n d (seq) add sequence o f items at end 1 s t . i n s e r t ( i d x , val) insert item at index 1 s t . remove (val) remove first item with value val 1 s t . p o p ([idx]) —»value remove & return item at index idx (default last) \1st.sort() lst.reverse() sort / reverse liste in place : () d.values del d[key] ( ) [ U e r able views d . p o p i t e m ( ) — (key, value) d . g e t (key/,default]) — value s . a d d (key) s . r e m o v e (key) s . d i s c a r d (key) s . c l e a r ( ) Advanced. name with parentheses which does the call *sequence "w", encoding=utf8") / J opening mode writing f.write ("coucou") f.writelines (list o f lines) 0 encoding of chars for text read ict on Strings (sep) — (before,sep,after) . c o u n t (sub/,start/,end]]) s.partition . i n d e x (sub/,start[,end]]) s.£E£ind (subl,start/,end]]) 'b' 't' utf8 latinil formating directives ascii "modele{} reading # read empty string if end of file f.read(/n]) — next chars if n not specified, read up to end ! f.readlines f.readline() s . s w a p c a s e () s.title() s.lower() . upper ( ) s . c e n t e r ([width,fill]) s.capitalize() .casefold() ([width]) s.z£ill ([width fill]) s.rjust . 1 j u s t ([width,fill]) . e n c o d e (encoding) s.split (/sep]) Ss. j o i n (seq) files: ' w ' write ' a ' append '4+' 'x' EEE o'r’ 0 3% J . i s . . . ( ) tests on chars categories (ex. s . i s a l p h a ( ) ) open("file.txt", , cf. modules o s , o s . p a t h and pathlibo one argumentper parameter Operations (prefix/,start[,end]]) .startswith . e n d s w i t h (suffix/,start[,end]]) s . s t r i p ([chars]) \. (key/default]) = value ) \ _ s . p o p ( ) name of file o n disk (+path...) Function Call fect ( 3 , i + 2 , 2 * i ) # this i s the use o f function storing data on disk, and reading it back file variable (x,y, z, *args, a=3,b=5, **kwargs) : storage/use of returned value I'd for operations fct J s . u p d a t e (s2) s . c o p y ( ) Fk = r | — union (vertical bar char) & — intersection d . p o p (key/,default]) — value \d . setdefault gee | default values, *args variable positional arguments (—tuple), **kwargs variable named arguments (—dict) Operators: d . i t e m s ( ) J keys/values/associations | """documentation""" # statements block, res computation, elc. «| r e t u r n res-<— result value of the call, if no computed result to return: r e t u r n None / # parameters and all variables of this block exist only in the block and during the function call (think of a “black box”) ~| J. Operators also exist as methods. on J. F u n c t i o n Definition fot ( x , y , z ) : Advanced: d e f — ~ — difference/symmetric diff. < < = > > = — inclusion relations { update/add associations range (2,12,3)—>25811 range (20,5,-5)— 201510 \ ! range provides an immutable sequence of int constructed as needed copy d . u p d a t e (42) J. Integer Sequences # start default 0, end not included in sequence, step signed, default 1 c o p y. copy ( c ) — shallow copy of container \ copy . deepcopy ( c ) — deep copy of container d [key] — value enumerate ( l s t ) : in r a n g e (5)—> 0 1 2 3 4 r a n g e ( 3 , 8 ) —> 3 4 5 6 7 Specific to ordered sequences containers (lists, tuples, strings, bytes...) r e v e r s e d ( c ) — inversed iterator ~~ ¢ * 5 — duplicate c + c 2 — concatenate c . i n d e x (val) — position c . c o u n t ( v a l ) — events count ( ¥ modify original list lost) range (/start,| end [,step]) ( a l l ( c ) — T r u e if all c items evaluated to true, else F a l s e a n y ( c ) — T r u e if a t least one item o f c evaluated true, else F a l s e QL ov- tons ondDictionaries | .clear() d [key] =value than 15, memorizing of lost values. val > 15: l o s t . append ( v a l ) 15 1st [idx] ("modif:",1lst,"-lost:", idx,val (for operations use keys. enumerate ( c ) — iterator o n (index, value) z i p ( c l , c2...) — iterator on tuples containing c_ items at same index import oo Algo: limit values greater range ( l e n ( l s t ) ) : Go simultaneously over sequence's index and values: Note: For dictionaries a n d sets, these sorted copy EEE sorted in val = lst [idx] ("Instructions:") (1en (ec) — items count min (c) max(c) sum(c) number of e in the string. "'e'") access items around index (before / after) 0 items separator, default space end o f print, default new line print to file, default standard output # input always returns a string, convert it to required type L cnt, Go over sequence's index o modify item at index items to display : literal values, variables, expressions p r i n t options: 0 ("found", loop on dict/set & loop on keys sequences use slices to loop on a subset of a sequence :",x,",",yt+4) rd oo cnt = ent + 1 print ("v=",3,"em i initializations before the loop Some text" =1 Id print Lo | = loop, variable, assignment managed by f o r statement f o r 'c¢'in s : Algo: count "e": c¢ = = if Algo: 8" i = 1 0 0 , — . I S— # make condition variable change ! sequence: in G o over sequence’s values exit ("sum:",s) print N next, . . var ——| statements block n break next iteration continue j e l s e block for normal i } , n for immediate exit : 0 ; initializations before the loop J condition with a least one variable value (here i ) $= (QUEEUNRKeloTRSIE111 [ T l statements block executed for each item o f a container o r iterator J # good habit : don't modify loop variable I'd (/n]) (/size]) resize f.truncate £ . £ f l u s h ( ) write cache reading/writing progress sequentially in the file, modifiable with. f . s e e k (position],origin]) ( ) — position f.tell Very common: opening with a guarded block w i t h o p e n ( . . ) a s £f: (automatic closing) and reading loop on lines for line in £ o f a text file: # processing o f 1ine {}".format (x,y, r) » str " {selection : formatting ! conversion} " a Selection : — list o f nextlines — next line ® text mode t by default (read/write s t r ) , possible binary mode b (read/write b y t e s ) . Convert from/to required type ! f.close() # dont forget to close the file after use ! {} values to format ( " { : + 2 . 3 f } " . format (45.72793) 2 8 | nom 0 - om format ( 8 , " t o t o " ) £4 >! S| toto’ > n " as { x ' r } " . f o r m a t ( x _= "T TI ' m " ) 4 [key] 0[2] o >'+45.728" = J "{1:>10s}". —'""I\'m""' Formatting : fill char alignment sign mini width. precision~maxwidth A <> AN= + — space integer: b binary, ¢ hype A 0 at start for filling with 0 char, d decimal (default), o octal, x or X hexa... float: e or E exponential, £ or F fixed point, g or G appropriate (default), % percent string: s ... J. \ ° Conversion : s (readable text) or r (literal representation)