Download Python Cheat Sheet. List of standard Python code and more Summaries Physics in PDF only on Docsity! ©2012-2015 - Laurent Pointal | Mémento v2.0.6 Python 3 Cheat Sheet Latest version on : License Creative Commons Attribution + https://perso.limsi. fr{pointal/python:memento integer, float, boolean, string, bytes EESINT IID ( = ordered sequences, fast index access, repeatable values Container Types int 783 0 -192 Qb010 00642 OxF3 list [1,5,9] ["x",11,8.9] ["mot "] zero inary octal ex 1,5,9 11,"y",7.4 "mot", float 9.23 0.0 -1.7e-6 ™ a kuple ( 2 : ¥ — ( ) bool True False xi0° on modifiable values (immutables) expression with only comas > tuple str bytes (ordered sequences of chars / bytes) str "one\nTwo" Multiline string: ek ta iori order, f h key is uni ‘escaped new line wrx EY \EZ ey containers, no a priori order, fast key access, each key is unique "I\tm' 1\t2\t3""" dictionary dict {"key":"value"} dict (a=3,b=4,k="v") escaped * escaped tab (key/value associations) {1: "one", 3:"three",2:"two",3.14:"n"} bytes b"toto\xfe\775" collection set {"key1","key2"} {1,9,3,0} hexadecimal octal ? immutables ? keys=hashable values (base types, immutables...) frozenset immutable set se ea mes int ("15") — 15 Eype (expression) a.2A.2. followed by auzA.2 0.9 int ("3£",16) — 63 can specify integer number base in 2" parameter S diacritics allowed but should be avoided int (15.56) — 15 truncate decimal part float ("-11.24e8") — -1124000000.0 round(15.56,1)»15.6 rounding to 1 decimal (0 decimal — integer number) bool (x) False for null x, empty container x , None or False x ; True for other x stx(x)—".." representation string of x for display (cf. formatting on the back) chr(64)3'@' ord('@') 364 code © char repr(x)—".." literal representation string of x bytes([72,9,64]) — b'H\t@' list ("abe") > ['a','b','c'] dict ([(3,"three"), (1,"one")]) — {1:'one',3:'three'} set (["one", "two"]) > {'one', 'two'} separator stx and sequence of str — assembled str ' join(['toto', '12', 'pswd']) > 'toto:12:pswd' str splitted on whitespaces > list of str "words with spaces".split() > ['words', 'with','spaces'] str splitted on separator str — list of str "1,4,8,2".split(",") > ['1','4','8','2'] sequence of one type list of another type (via list comprehension) [int (x) for x in ('1','29','-3')] > [1,29,-3] J Sequence Containers Indexing = language keywords forbidden = lower/UPPER case discrimination © a toto x7 y_max BigOne ® 8y and for Variables assignment @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+8+sin(y) C=0 assignment to same value y,Z,L=9.2,-7.6, 0 multiple assignments a,b=b,a_ values swap a, *b=seq | unpacking of sequence in *a,b=seq J itemand list 3 increment x: x x=None «undefined » constant value = decrement = (de xX =~ remove name x negative index -3 Items count Individual access to items via 1st [index] positive index 2: 3: len(l1st)75 1st[0]710 = = first one 1st[1]720 1st=[10 20, 30; 40; 50]: ; Ast[-1]50 = lastone 1st [-2] 40 positive slice 2 3 4 5; findex from 0 On mutable sequences (ist), remove with negative slice = 3.2 here from 0 to 4) del 1st [3] and modify with assignment ‘Access to sub-sequences via 1st [start slice: end ep] ist [4]=25 Ast [:-1]+[10,20,30,40] 1st{::-1]+[50,40,30,20,10] 1st[{1:3]+[20,30] 1st[:3]+[10,20,30] ist [1:-1]>[20, 30,40] ist[ 2]>[50, 30,10] Ast [-3:-1]+[30,40] 1st[3:]+[40,50] Ast [::2]+[10,30,50] Ast [:]+[10, 20, 30, 40, 50] shallow copy of sequence Missing slice indication — from start / up to end. On mutable sequences (List), remove with del 1st [3:5] and modify with assignment st [1: 4]=[15,25] Boolean Logic Comparisons : < > <= (boolean results) s a and b bgical and both simulta- -neously ICT Te module truce file truc.py Modules/Names Imports from monmod import noml,nom2 as fct direct access to names, renaming with as import monmod — «access via monmod.nom1... modules and packages searched in python path (cf sys .path) Conditional Statement [parent statement : ~2|statement block 1... logical or €or other a or b bogi or both @ pitfall : and and ox return value of a or of b (under shortcut evaluation). > ensure that a and are booleans. not a logical not Statement block executed only if a condition is true if logical condition: —— statements block " zg i g S|parent statement : &|_J statement block2... z : next statement after block 1 True . cond spaces Can go with several elif, elif... and only one False } True and False constants 1 configure editor to insert 4 spaces in final else. Only the blocs of fst true : place of an indentation tab. dit ted Kid" condition is executed. etl? ayer 65: floating numbers... approximated values angles in radians with a var x: state="Retired’| a - i 5 5 if bool else: Operators: + - * / // & ** from math import sin,pi.. || + boot & state="Active" Priority (...) = ft fa sin (pi/4) +0.707... . imeger+ remainder | cos (2*pi/3)>-0. 4999... Signaling an error @ matrix x pyrioni.s+numpy sqrt (81)+9.0 v raise FrcClass(...) (145.3) *2412.6 log (e**2) 2.0 Errors processing: normal abs (-3.2)+3.2 ceil (12.5)+13 try raise X( round (3.57,1)+3.6 floor (12.5) 712 oF normal proce ising block (Presse pow(4,3)+64.0 ; ‘modules math, statistics, random, || except Exception as e: finally block for final processing § usual order of operations decimal, fractions, numpy, etc. (¢f: doc) )\—> error processing block in all cases,