Python Cheat Sheet
Introduction to Programming (University of California, Irvine)
Scan to open on Studocu
Studocu is not sponsored or endorsed by any college or university
Downloaded by Kali (kalizilla765@[Link])
Mémento v1.2.2 Official Python documentation on
©2012-2013 - Laurent Pointal
Licence Creative Commons Attribution 2 Python 3 Cheat Sheet [Link]
integer, float, boolean, string Base Types Container Types
◾ ordered sequence, fast index access, repeatable values
int 783 0 -192 list [1,5,9] ["x",11,8.9] ["word"] []
float 9.23 0.0 -1.7e-6 tuple (1,5,9) 11,"y",7.4 ("word",) ()
bool True False 10-6 immutable expression with just comas
str as an ordered sequence of chars
str "One\nTwo" 'I\'m' ◾ no a priori order, unique key, fast key access ; keys = base types or tuples
new line ' escaped dict {"key":"value"} {}
dictionary
{1:"one",3:"three",2:"two",3.14:"π"}
multiline """X\tY\tZ key/value associations
immutable, 1\t2\t3"""
ordered sequence of chars tab char set {"key1","key2"} {1,9,3,0} set()
for variables, functions, Identifiers type(expression) Conversions
modules, classes… names
a‥zA‥Z_ followed by a‥zA‥Z_0‥9
int("15") can specify integer number base in 2nd parameter
◽ diacritics allowed but should be avoided int(15.56) truncate decimal part (round(15.56) for rounded integer)
◽ language keywords forbidden float("-11.24e8")
◽ lower/UPPER case discrimination
str(78.3) and for litteral representation repr("Text")
☺ a toto x7 y_max BigOne see other side for string formating allowing finer control
☹ 8y and
bool use comparators (with ==, !=, <, >, …), logical boolean result
list("abc") use each element ['a','b','c']
Variables assignment
from sequence
x = 1.2+8+sin(0) dict([(3,"three"),(1,"one")]) {1:'one',3:'three'}
value or computed expression use each element
variable name (identifier) set(["one","two"]) from sequence {'one','two'}
y,z,r = 9.2,-7.6,"bad"
":".join(['toto','12','pswd']) 'toto:12:pswd'
variables container with several
joining string sequence of strings
names values (here a tuple)
increment "words with spaces".split() ['words','with','spaces']
x+=3 decrement x-=2
"1,4,8,2".split(",") ['1','4','8','2']
x=None « undefined » constant value splitting string
for lists, tuples, strings, … Sequences indexing
negative index -6 -5 -4 -3 -2 -1 len(lst) 6
positive index 0 1 2 3 4 5 individual access to items via [index]
lst=[11, 67, "abc", 3.14, 42, 1968] lst[1]→67 lst[0]→11 first one
positive slice0 1 2 3 4 5 6 lst[-2]→42 lst[-1]→1968 last one
negative slice -6 -5 -4 -3 -2 -1 access to sub-sequences via [start slice:end slice:step]
lst[:-1]→[11,67,"abc",3.14,42] lst[1:3]→[67,"abc"]
lst[1:-1]→[67,"abc",3.14,42] lst[-3:-1]→[3.14,42]
lst[::2]→[11,"abc",42] lst[:3]→[11,67,"abc"]
lst[:]→[11,67,"abc",3.14,42,1968] lst[4:]→[42,1968]
Missing slice indication → from start / up to end.
On mutable sequences, usable to remove del lst[3:5] and to modify with assignment lst[1:4]=['hop',9]
Boolean Logic Statements Blocks statements block executed Conditional Statement
Comparators: < > <= >= == != parent statement: only if a condition is true
= ≠
a and b logical and statements block 1… if logical expression:
indentation !
both simultaneously ⁝ statements block
a or b logical or parent statement:
can go with several elif, elif... and only one final else,
one or other or both statements block 2…
not a logical not
⁝
example :
True true constant value if x==42:
False false constant value next statement after block 1 # block if logical expression x==42 is true
print("real truth")
elif x>0:
☝ floating point numbers… approximated values! angles in radians Maths # else block if logical expression x>0 is true
Operators: + - * / // % ** from math import sin,pi… print("be positive")
× ÷ ab elif bFinished:
integer ÷ ÷ remainder
sin(pi/4)→0.707… # else block if boolean variable bFinished is true
cos(2*pi/3)→-0.4999… print("how, finished")
(1+5.3)*2→12.6
acos(0.5)→1.0471… else:
abs(-3.2)→3.2 sqrt(81)→9.0 √ # else block for other cases
round(3.57,1)→3.6 log(e**2)→2.0 etc. (cf doc) print("when it's not")
Downloaded by Kali (kalizilla765@[Link])
statements block executed as long Conditional loop statement statements block executed for each Iterative loop statement
as condition is true item of a container or iterator
while logical expression: for variable in sequence:
s = 0
statements block Loop control statements block
i = 1 initializations before the loop break Go over sequence's values
immediate exit
condition with at least one variable value (here i) continue s = "Some text" initializations before the loop
next iteration cnt = 0
while i <= 100: loop variable, value managed by for statement
# statement executed as long as i ≤ 100 i= for c in s:
s = s + i**2
i = i + 1 ☝ make condition variable change
s= i ∑ if c == "e":
cnt = cnt + 1
Count number of
e in the string
i=
print("found",cnt,"'e'")
print("sum:",s) computed result after the loop loop on dict/set = loop on sequence of keys
☝ be careful of inifinite loops ! use slices to go over a subset of the sequence
Go over sequence's index
Display / Input ◽ modify item at index
print("v=",3,"cm :",x,",",y+4) ◽ access items around index (before/after)
lst = [11,18,9,12,23,4,17]
items to display: litteral values, variables, expressions lost = []
print options:
for idx in range(len(lst)):
val = lst[idx] Limit values greater
◽ sep=" " (items separator, default space) if val > 15: than 15, memorization
◽ end="\n" (end of print, default new line) [Link](val) of lost values.
◽ file=f (print to file, default standard output) lst[idx] = 15
s = input("Instructions:") print("modif:",lst,"-lost:",lost)
☝ input always returns a string, convert it to required type Go simultaneously over sequence's index and values:
(cf boxed Conversions on on ther side). for idx,val in enumerate(lst):
len(c)→ items count Operations on containers frequently used in Generator of int sequences
min(c) max(c) sum(c) Note: For dictionaries and set, these for iterative loops default 0 not included
sorted(c) → sorted copy operations use keys. range([start,]stop [,step])
val in c → boolean, membersihp operator in (absence not in) range(5) 0 1 2 3 4
enumerate(c)→ iterator on (index,value)
Special for sequence containeurs (lists, tuples, strings) :
range(3,8) 3 4 5 6 7
reversed(c)→ reverse iterator c*5 → duplicate c+c2 → concatenate range(2,12,3) 2 5 8 11
[Link](val) → position [Link](val)→ events count range returns a « generator », converts it to list to see
the values, example:
☝ modify original list Operations on lists print(list(range(4)))
[Link](item) add item at end
[Link](seq) add sequence of items at end
[Link](idx,val) insert item at index
function name (identifier) Function definition
[Link](val) remove first item with value named parameters
[Link](idx) remove item at index and return its value def fctname(p_x,p_y,p_z):
[Link]() [Link]() sort / reverse list in place
"""documentation"""
Operations on dictionaries Operations on sets
# statements block, res computation, etc.
d[key]=value [Link]() Operators: return res result value of the call.
| → union (vertical bar char) if no computed result to
d[key]→value del d[clé] & → intersection
☝ parameters and all of this bloc
only exist in the block and during return: return None
[Link](d2) update/add - ^ → difference/symetric diff
[Link]() associations the function call ("black box")
< <= > >= → inclusion relations
[Link]() views on keys, values [Link](s2) Function call
[Link]() associations [Link](key) [Link](key) r = fctname(3,i+2,2*i)
[Link](clé) [Link](key) one argument per parameter
retrieve returned result (if necessary)
storing data on disk, and reading it back Files
f = open("[Link]","w",encoding="utf8") Strings formating
formating directives values to format
file variable name of file opening mode encoding of "model {} {} {}".format(x,y,r) str
for operations on disk ◽ 'r' read chars for text "{selection:formating!conversion}"
(+path…) ◽ 'w' write files: ◽ Selection : "{:+2.3f}".format(45.7273)
◽ 'a' append… utf8 ascii 2 →'+45.727'
Examples
cf functions in modules os and [Link] latin1 … x "{1:>10s}".format(8,"toto")
[Link]
writing empty string if end of file reading 4[key] →' toto'
0[2] "{!r}".format("I'm")
[Link]("hello") s = [Link](4)if char count not ◽ Formating : →'"I\'m"'
☝ text file → read /write only read next specified, read fillchar alignment sign [Link]~maxwidth type
strings, convert from/to required line whole file
type. s = [Link]() <>^= + - space 0 at start for filling with 0
[Link]() ☝ don't forget to close file after use integer: b binary, c char, d decimal (default), o octal, x or X hexa…
Pythonic automatic close : with open(…) as f: float: e or E exponential, f or F fixed point, g or G appropriate (default),
very common: iterative loop reading lines of a text file % percent
for line in f : string : s …
# line processing block ◽ Conversion : s (readable text) or r (litteral representation)
Downloaded by Kali (kalizilla765@[Link])