Python 3 Cheat Sheet
Python 3 Cheat Sheet
Python 3 Cheat Sheet
5
License Creative Commons Attribution 4
Base Types
integer, float, boolean, string, bytes
int 783 0 -192 0b010 0o642 0xF3
binary
null
octal
"""X\tY\tZ
1\t2\t3"""
escaped '
escaped tab
Variables assignment
x=1.2+8+sin(y)
a=b=c=0 assignment to same value
y,z,r=9.2,-7.6,0 multiple assignments
a,b=b,a values swap
a,*b=seq unpacking of sequence in
*a,b=seq item and list
and
x+=3
increment x=x+3
*=
x-=2
/=
decrement x=x-2
%=
x=None undefined constant value
del x
remove name x
negative index
positive index
-5
0
key containers, no a priori order, fast key acces, each key is unique
dictionary
0
-5
1
-4
set {"key1","key2"}
2
-3
3
-2
{}
{1,9,3,0}
set()
empty
Conversions
type(expression)
int("15") 15
nd
int("3f",16) 63
can specify integer number base in 2 parameter
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
str(x) "" representation string of x for display (cf. formating on the back)
chr(64)'@' ord('@')64
code char
repr(x) "" literalrepresentation string of x
bytes([72,9,64]) b'H\t@'
list("abc") ['a','b','c']
dict([(3,"three"),(1,"one")]) {1:'one',3:'three'}
set(["one","two"]) {'one','two'}
separator str 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 comprehension list)
[int(x) for x in ('1','29','-3')] [1,29,-3]
-4
1
dict(a=3,b=4,k="v")
positive slice
negative slice
dict {"key":"value"}
collection
Identifiers
""
b""
immutables
hexadecimal octal
Container Types
["mot"]
[]
("mot",)
()
'I\'m'
bytes b"toto\xfe\775"
hexa
4
-1
index from 0
(here from 0 to 4)
lst[0]10
lst[-1]50
first one
last one
lst[1]20
lst[-2]40
lst[:3][10,20,30]
lst[:-1][10,20,30,40] lst[::-1][50,40,30,20,10] lst[1:3][20,30]
lst[1:-1][20,30,40]
lst[-3:-1][30,40] lst[3:][40,50]
lst[::-2][50,30,10]
lst[::2][10,30,50]
lst[:][10,20,30,40,50] shallow copy of sequence
Missing slice indication from start / up to end.
On mutable sequences (list), remove with del lst[3:5] and modify with assignment lst[1:4]=[15,25]
-neously
a or b
or both
pitfall: and and or return value of a or
of b (under shortcut evaluation).
ensure that a and b are booleans.
logical not
True
False
integer remainder
@ matrix python3.5+numpy
(1+5.3)*212.6
abs(-3.2)3.2
round(3.57,1)3.6
pow(4,3)64.0
usual priorities
parent statement:
statement block 1
parent statement:
statement block2
not a
Operators: + - * / // % **
ab
Priority ()
Statements Blocks
indentation!
Boolean Logic
Comparators: < > <= >= == !=
(boolean results)
=
both simultalogical
and
a and b
Maths
from math import sin,pi
angles in radians
sin(pi/4)0.707
cos(2*pi/3)-0.4999
sqrt(81)9.0
log(e**2)2.0
ceil(12.5)13
floor(12.5)12
Modules/Names Imports
from monmod import nom1,nom2 as fct
Conditional Statement
yes
if logical condition:
statements block
no
yes
?
no
if age<=18:
state="Kid"
elif age>65:
state="Retired"
with a var x:
else:
if bool(x)==True: if x:
state="Active"
if bool(x)==False: if not x:
Signaling an error:
raise ExcClass()
Errors processing:
try:
normal procesising block
except Exception as e:
error processing block
Exceptions on Errors
normal
raise X()
processing
error
processing
errorraise
processing
yes
Loop Control
break
immediate exit
continue next iteration
no
Algo:
i=100
s= i 2
i=1
print("v=",3,"cm:",x,",",y+4)
Display
Input
s = input("Instructions:")
input always returns a string, convert it to required type
(cf. boxed Conversions on the other side).
Operations on Lists
lst.append(val)
add item at end
lst.extend(seq)
add sequence of items at end
lst.insert(idx,val)
insert item at index
lst.remove(val)
remove first item with value val
lst.pop([idx])value
remove & return item at index idx (default last)
lst.sort() lst.reverse() sort / reverse liste in place
modify original list
d.setdefault(key[,default])value
Operations on Sets
Operators:
| union (vertical bar char)
& intersection
- ^ diffrence/symetric diff.
< <= > >= inclusion relations
Operators also exist as methods.
s.update(s2) s.copy()
s.add(key) s.remove(key)
s.discard(key) s.clear()
s.pop()
Files
f = open("file.txt","w",encoding="utf8")
file variable
for operations
name of file
on disk
(+path)
opening mode
'r' read
'w' write
'a' append
cf. modules os, os.path and pathlib '+' 'x' 'b' 't'
encoding of
chars for text
files:
utf8 ascii
latin1
writing
f.write("coucou")
f.read([n])
next chars
reading
f.tell()position
finish
Operations on Dictionaries
d.clear()
d[key]=value
del d[key]
d[key] value
d.update(d2) update/add
associations
d.keys()
d.values() iterable views on
d.items() keys/values/associations
d.pop(key[,default]) value
d.popitem() (key,value)
d.get(key[,default]) value
f.seek(position[,origin])
Very common: opening with a guarded block
with open() as f:
(automatic closing) and reading loop on lines
for line in f:
of a text file:
# processing ofline
lst = [11,18,9,12,23,4,17]
lost = []
Algo: limit values greater
for idx in range(len(lst)):
than 15, memorizing
val = lst[idx]
of lost values.
if val > 15:
lost.append(val)
lst[idx] = 15
print("modif:",lst,"-lost:",lost)
Integers Sequences
Function Definition
def fct(x,y,z):
fct
"""documentation"""
# statements block, res computation, etc.
result value of the call, if no computed
return res
Function Call
r = fct(3,i+2,2*i)
storage/use of
returned value
Advanced:
*sequence
**dict
fct()
fct
Operations on Strings
s.startswith(prefix[,start[,end]])
s.endswith(suffix[,start[,end]]) s.strip([chars])
s.count(sub[,start[,end]]) s.partition(sep) (before,sep,after)
s.index(sub[,start[,end]]) s.find(sub[,start[,end]])
s.is() tests on chars categories (ex. s.isalpha())
s.upper()
s.lower()
s.title()
s.swapcase()
s.casefold()
s.capitalize()
s.center([width,fill])
s.ljust([width,fill]) s.rjust([width,fill]) s.zfill([width])
s.encode(encoding)
s.split([sep]) s.join(seq)
formating directives
values to format
"modele{} {} {}".format(x,y,r)
"{selection:formating!conversion}"
Formating
str
Selection :
"{:+2.3f}".format(45.72793)
2
'+45.728'
nom
"{1:>10s}".format(8,"toto")
0.nom
'
toto'
4[key]
"{x!r}".format(x="I'm")
0[2]
'"I\'m"'
Formating :
fill char alignment sign mini width.precision~maxwidth type
Examples
<>^=
0 at start for filling with 0
+ - space
integer: b binary, c char, d decimal (default), o octal, x or X hexa
float: e or E exponential, f or F fixed point, g or G appropriate (default),
string: s
% percent
Conversion : s (readable texte) or r (literal representation)