Python Notes PDF
Python Notes PDF
Notes/Cheat
Sheet
Comments
Operators
#
from
the
hash
symbol
to
the
end
of
a
line
Operator
Functionality
+
Addition
(also
string,
tuple,
Code
blocks
list
concatenation)
Delineated
by
colons
and
indented
code;
and
-
Subtraction
(also
set
difference)
not
the
curly
brackets
of
C,
C++
and
Java.
*
Multiplication
(also
string,
def
is_fish_as_string(argument):
#
a
function
tuple,
list
replication)
if
argument:
/
Division
return
fish
%
Modulus
(also
a
string
format
else:
function,
but
use
deprecated)
return
not
fish
//
Integer
division
rounded
towards
Note:
Four
spaces
per
indentation
level
is
minus
infinity
the
Python
standard.
Never
use
tabs:
mixing
**
Exponentiation
tabs
and
spaces
produces
hard-to-find
errors.
=,
-=,
+=,
Assignment
operators
Set
your
editor
to
convert
tabs
to
spaces.
/=,
*=,
%=,
//=,
Line
breaks
**=
Typically,
a
statement
must
be
on
one
line.
==,
!=,
<,
Boolean
comparisons
Bracketed
code
-
(),
[]
or
{}
-
can
be
split
<=,
>=,
>
across
lines;
or
use
a
backslash
\
at
the
end
and,
or,
Boolean
operators
of
a
line
can
be
used
to
continue
a
statement
not
on
to
the
next
line.
in,
not
in
Membership
test
operators
is,
is
not
Object
identity
operators
Naming
conventions
|,
^,
&,
~
Bitwise:
or,
xor,
and,
compliment
Style
Use
<<,
>>
Left
and
right
bit
shift
StudlyCase
Class
names
;
Inline
statement
separator
joined_lower
Identifiers,
functions;
and
#
inline
statements
discouraged
class
methods,
attributes
Hint:
float('inf')
always
tests
as
larger
_joined_lower
Internal
class
attributes
than
any
number,
including
integers.
__joined_lower
Private
class
attributes
#
this
use
not
recommended
Modules
joined_lower
Constants
Modules
open
up
a
world
of
Python
extensions
ALL_CAPS
that
can
be
imported
and
used.
Access
to
the
functions,
variables
and
classes
of
a
module
Basic
object
types
(not
a
complete
list)
depend
on
how
the
module
was
imported.
Type
Examples
Import
method
Access/Use
syntax
None
None
#
singleton
null
object
import
math
math.cos(math.pi/3)
Boolean
True,
False
import
math
as
m
m.cos(m.pi/3)
integer
-1,
0,
1,
sys.maxint
#
import
using
an
alias
long
1L,
9787L
#
arbitrary
length
ints
from
math
import
cos,\
cos(pi/3)
float
3.14159265
pi
inf,
float('inf')#
infinity
#
only
import
specifics
-inf
#
neg
infinity
from
math
import
*
log(e)
nan,
float('nan')#
not
a
number
#
BADish
global
import
complex
2+3j
#
note
use
of
j
Global
imports
make
for
unreadable
code!!!
string
'I
am
a
string',
"me
too"
'''multi-line
string''',
"""+1"""
Oft
used
modules
r'raw
string',
b'ASCII
string'
Module
Purpose
u'unicode
string'
datetime
Date
and
time
functions
tuple
empty
=
()
#
empty
tuple
time
(1,
True,
'dog')
#
immutable
list
math
Core
math
functions
and
the
list
empty
=
[]
#
empty
list
constants
pi
and
e
[1,
True,
'dog']
#
mutable
list
pickle
Serialise
objects
to
a
file
set
empty
=
set()
#
the
empty
set
os
Operating
system
interfaces
set(1,
True,
'a')#
mutable
os.path
dictionary
empty
=
{}
#
mutable
object
re
A
library
of
Perl-like
regular
{'a':
'dog',
7:
'seven,
True:
1}
expression
operations
file
f
=
open('filename',
'rb')
string
Useful
constants
and
classes
Note:
Python
has
four
numeric
types
(integer,
sys
System
parameters
and
functions
float,
long
and
complex)
and
several
sequence
numpy
Numerical
python
library
types
including
strings,
lists,
tuples,
pandas
DataFrames
for
Python
bytearrays,
buffers,
and
xrange
objects.
matplotlib
Plotting/charting
for
Python
Version:
7
January
2014
If
-
flow
control
if
condition:
#
for
example:
if
x
<
5:
statements
elif
condition:
#
optional
can
be
multiple
statements
else:
#
optional
statements
For
-
flow
control
for
x
in
iterable:
statements
else:
#
optional
completion
code
statements
While
-
flow
control
while
condition:
statements
else:
#
optional
completion
code
statements
Ternary
statement
id
=
expression
if
condition
else
expression
x
=
y
if
a
>
b
else
z
-
5
Some
useful
adjuncts:
pass
-
a
statement
that
does
nothing
continue
-
moves
to
the
next
loop
iteration
break
-
to
exit
for
and
while
loop
Trap:
break
skips
the
else
completion
code
Exceptions
flow
control
try:
statements
except
(tuple_of_errors):
#
can
have
multiple
statements
else:
#
optional
no
exceptions
statements
finally:
#
optional
all
circumstances
statements
Common
exceptions
(not
a
complete
list)
Exception
Why
it
happens
AsserionError
Assert
statement
failed
AttributeError
Class
attribute
assignment
or
reference
failed
IOError
Failed
I/O
operation
ImportError
Failed
module
import
IndexError
Subscript
out
of
range
KeyError
Dictionary
key
not
found
MemoryError
Ran
out
of
memory
NameError
Name
not
found
TypeError
Value
of
the
wrong
type
ValueError
Right
type
but
wrong
value
Raising
errors
Errors
are
raised
using
the
raise
statement
raise
ValueError(value)
Creating
new
errors
class
MyError(Exception):
def
__init__(self,
value):
self.value
=
value
def
__str__(self):
return
repr(self.value)
Version:
7
January
2014
Using
functions
When
called,
functions
can
take
positional
and
named
arguments.
For
example:
result
=
function(32,
aVar,
c='see',
d={})
Arguments
are
passed
by
reference
(ie.
the
objects
are
not
copied,
just
the
references).
Writing
a
simple
function
def
funct(arg1,
arg2=None,
*args,
**kwargs):
"""explain
what
this
function
does"""
statements
return
x
#
optional
statement
Note:
functions
are
first
class
objects
that
get
instantiated
with
attributes
and
they
can
be
referenced
by
variables.
Avoid
named
default
mutable
arguments
Avoid
mutable
objects
as
default
arguments.
Expressions
in
default
arguments
are
evaluated
when
the
function
is
defined,
not
when
its
called.
Changes
to
mutable
default
arguments
survive
between
function
calls.
def
nasty(value=[]):
#
<--
mutable
arg
value.append('a')
return
value
print
(nasty
())
#
-->
['a']
print
(nasty
())
#
-->
['a',
'a']
def
better(val=None):
val
=
[]
if
val
is
None
else
val
value.append('a')
return
value
Lambda
(inline
expression)
functions:
g
=
lambda
x:
x
**
2
#
Note:
no
return
print(g(8))
#
prints
64
mul
=
lambda
a,
b:
a
*
b
#
two
arguments
mul(4,
5)
==
4
*
5
#
-->
True
Note:
only
for
expressions,
not
statements.
Lambdas
are
often
used
with
the
Python
functions
filter(),
map()
and
reduce().
#
get
only
those
numbers
divisible
by
three
div3
=
filter(lambda
x:
x%3==0,
range(1,101))
Typically,
you
can
put
a
lambda
function
anywhere
you
put
a
normal
function
call.
Closures
Closures
are
functions
that
have
inner
functions
with
data
fixed
in
the
inner
function
by
the
lexical
scope
of
the
outer.
They
are
useful
for
avoiding
hard
constants.
Wikipedia
has
a
derivative
function
for
changeable
values
of
dx,
using
a
closure.
def
derivative(f,
dx):
"""Return
a
function
that
approximates
the
derivative
of
f
using
an
interval
of
dx,
which
should
be
appropriately
small.
"""
def
_function(x):
return
(f(x
+
dx)
-
f(x))
/
dx
return
_function
#
from
derivative(f,
dx)
f_dash_x
=
derivative(lambda
x:
x*x,
0.00001)
f_dash_x(5)
#
yields
approx.
10
(ie.
y'
=
2x)
5
An
iterable
object
The
contents
of
an
iterable
object
can
be
selected
one
at
a
time.
Such
objects
include
the
Python
sequence
types
and
classes
with
the
magic
method
__iter__(),
which
returns
an
iterator.
An
iterable
object
will
produce
a
fresh
iterator
with
each
call
to
iter().
iterator
=
iter(iterable_object)
Iterators
Objects
with
a
next()
(Python
2)
or
__next__()
(Python
3)
method,
that:
returns
the
next
value
in
the
iteration
updates
the
internal
note
of
the
next
value
raises
a
StopIteration
exception
when
done
Note:
with
the
loop
for
x
in
y:
if
y
is
not
an
iterator;
Python
calls
iter()
to
get
one.
With
each
loop,
it
calls
next()
on
the
iterator
until
a
StopIteration
exception.
x
=
iter('XY')
#
iterate
a
string
by
hand
print
(next(x))
#
-->
X
print
(next(x))
#
-->
Y
print
(next(x))
#
-->
StopIteration
Generators
Generator
functions
are
resumable
functions
that
work
like
iterators.
They
can
be
more
space
or
time
efficient
than
iterating
over
a
list,
(especially
a
very
large
list),
as
they
only
produce
items
as
they
are
needed.
def
fib(max=None):
"""
generator
for
Fibonacci
sequence"""
a,
b
=
0,
1
while
max
is
None
or
b
<=
max:
yield
b
#
<--
yield
is
like
return
a,
b
=
b,
a+b
[i
for
i
in
fib(10)]
#
-->
[1,
1,
2,
3,
5,
8]
Note:
a
return
statement
(or
getting
to
the
end
of
the
function)
ends
the
iteration.
Trap:
a
yield
statement
is
not
allowed
in
the
try
clause
of
a
try/finally
construct.
Messaging
the
generator
def
resetableCounter(max=None):
j
=
0
while
max
is
None
or
j
<=
max:
x
=
yield
j
#
<--
x
gets
the
sent
arg
j
=
j+1
if
x
is
None
else
x
x
=
resetableCounter(10)
print
x.send(None)
#
-->
0
print
x.send(5)
#
-->
5
print
x.send(None)
#
-->
6
print
x.send(11)
#
-->
StopIteration
Trap:
must
send
None
on
first
send()
call
Generator
expressions
Generator
expressions
build
generators,
just
like
building
a
list
from
a
comprehension.
You
can
turn
a
list
comprehension
into
a
generator
expression
simply
by
replacing
the
square
brackets
[]
with
parentheses
().
[i
for
i
in
xrange(10)]
#
list
comprehension
list(i
for
i
in
xrange(10))
#
generated
list
Version:
7
January
2014
Classes
Python
is
an
object-oriented
language
with
a
multiple
inheritance
class
mechanism
that
encapsulates
program
code
and
data.
Methods
and
attributes
Most
objects
have
associated
functions
or
methods
that
are
called
using
dot
syntax:
obj.method(arg)
Objects
also
often
have
attributes
or
values
that
are
directly
accessed
without
using
getters
and
setters
(most
unlike
Java
or
C++)
instance
=
Example_Class()
print
(instance.attribute)
Simple
example
import
math
class
Point:
#
static
class
variable,
point
count
count
=
0
def
__init__(self,
x,
y):
self.x
=
float(x)
self.y
=
float(y)
Point.count
+=
1
def
__str__(self):
return
\
'(x={},
y={})'.format(self.x,
self.y)
def
to_polar(self):
r
=
math.sqrt(self.x**2
+
self.y**2)
theta
=
math.atan2(self.y,
self.x)
return(r,
theta)
#
static
method
trivial
example
...
def
static_eg(n):
print
('{}'.format(n))
static_eg
=
staticmethod(static_eg)
#
Instantiate
9
points
&
get
polar
coords
for
x
in
range(-1,
2):
for
y
in
range(-1,
2):
p
=
Point(x,
y)
print
(p)
#
uses
__str__()
method
print
(p.to_polar())
print
(Point.count)
#
check
static
variable
Point.static_eg(9)
#
check
static
method
The
self
Class
methods
have
an
extra
argument
over
functions.
Usually
named
'self';
it
is
a
reference
to
the
instance.
It
is
not
used
in
the
method
call;
and
is
provided
by
Python
to
the
method.
Self
is
like
'this'
in
C++
&
Java
Public
and
private
methods
and
variables
Python
does
not
enforce
the
public
v
private
data
distinction.
By
convention,
variables
and
methods
that
begin
with
an
underscore
should
be
treated
as
private
(unless
you
really
know
what
you
are
doing).
Variables
that
begin
with
double
underscore
are
mangled
by
the
compiler
(and
hence
more
private).
Inheritance
class
DerivedClass1(BaseClass):
statements
class
DerivedClass2(module_name.BaseClass):
statements
Multiple
inheritance
class
DerivedClass(Base1,
Base2,
Base3):
statements
Decorators
Technically,
decorators
are
just
functions
(or
classes),
that
take
a
callable
object
as
an
argument,
and
return
an
analogous
object
with
the
decoration.
We
will
skip
how
to
write
them,
and
focus
on
using
a
couple
of
common
built
in
decorators.
Practically,
decorators
are
syntactic
sugar
for
more
readable
code.
The
@wrapper
is
used
to
transform
the
existing
code.
For
example,
the
following
two
method
definitions
are
semantically
equivalent.
def
f(...):
...
f
=
staticmethod(f)
@staticmethod
def
f(...):
...
Getters
and
setters
Although
class
attributes
can
be
directly
accessed,
the
property
function
creates
a
property
manager.
class
Example:
def
__init__(self):
self._x
=
None
def
getx(self):
return
self._x
def
setx(self,
value):
self._x
=
value
def
delx(self):
del
self._x
x
=
property(getx,
setx,
delx,
"Doc
txt")
Which
can
be
rewritten
with
decorators
as:
class
Example:
def
__init__(self):
self._x
=
None
@property
def
x(self):
"""Doc
txt:
I'm
the
'x'
property."""
return
self._x
@x.setter
def
x(self,
value):
self._x
=
value
@x.deleter
def
x(self):
del
self._x