Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Title: Python Notes For Beginers
Description: By This Notes you can master python simple programas.This notes is made by reffering many books and experts made this out.check out this note will be very useful in your academics./
Description: By This Notes you can master python simple programas.This notes is made by reffering many books and experts made this out.check out this note will be very useful in your academics./
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
Python Notes/Cheat Sheet
Comments
# from the hash symbol to the end of a line
Code blocks
Delineated by colons and indented code; and not the
curly brackets of C, C++ and Java
...
Never use tabs: mixing tabs and spaces
produces hard-to-find errors
...
Line breaks
Typically, a statement must be on one line
...
Naming conventions
Style
Use
StudlyCase
Class names
joined_lower
Identifiers, functions; and class
methods, attributes
_joined_lower
Internal class attributes
__joined_lower
Private class attributes
# this use not recommended
joined_lower
Constants
ALL_CAPS
Basic object types (not a complete list)
Type
Examples
None
None
# singleton null object
Boolean
True, False
integer
-1, 0, 1, sys
...
14159265
inf, float('inf')
# infinity
-inf
# neg infinity
nan, float('nan') # not a number
complex
2+3j
# note use of j
string
'I am a string', "me too"
'''multi-line string''', """+1"""
r'raw string', b'ASCII string'
u'unicode string'
tuple
empty = ()
# empty tuple
(1, True, 'dog') # immutable list
list
empty = []
# empty list
[1, True, 'dog'] # mutable list
set
empty = set() # the empty set
set(1, True, 'a') # mutable
dictionary
empty = {}
# mutable object
{'a': 'dog', 7: 'seven’, True: 1}
file
f = open('filename', 'rb')
Note: Python has four numeric types (integer, float, long
and complex) and several sequence types including
strings, lists, tuples, bytearrays, buffers, and xrange
objects
...
Modules
Modules open up a world of Python extensions that can
be imported and used
...
Import method
Access/Use syntax
import math
math
...
pi/3)
import math as m
m
...
pi/3)
# import using an alias
from math import cos,pi
cos(pi/3)
# only import specifics
from math import *
log(e)
# BADish global import
Global imports make for unreadable code!!!
Oft used modules
Module
Purpose
datetime
Date and time functions
time
math
Core math functions and the constants pi
and e
pickle
Serialise objects to a file
os
Operating system interfaces
os
...
value = value
def __str__(self):
return repr(self
...
For example, all functions have the built-in attribute
__doc__, which returns the doc string defined in the
function's source code
...
They are references to objects; and often called
identifiers
...
But most are mutable (including: list, set,
dictionary, NumPy arrays, etc
...
Booleans and truthiness
Most Python objects have a notion of "truth"
...
You can use bool() to discover the truth status of an
object
...
if container:
# test not empty
# do something
while items:
# common looping idiom
item = items
...
Comparisons
Python lets you compare ranges, for example
if 1 < x < 100: # do something
...
They can be searched,
indexed and iterated much like lists (see below)
...
a = ()
# the empty tuple
a = (1,) # " note comma # one item tuple
a = (1, 2, 3)
# multi-item tuple
a = ((1, 2), (3, 4))
# nested tuple
a = tuple(['a', 'b'])
# conversion
Note: the comma is the tuple constructor, not the
parentheses
...
The Python swap variable idiom
a, b = b, a
# no need for a temp variable
This syntax uses tuples to achieve its magic
...
upper()
# STRING
s = 'fred'+'was'+'here'
# concatenation
s = ''
...
print ((digits, hexdigits, letters,
lowercase, uppercase, punctuation))
Old school string formatting (using % oper)
print ("It %s %d times" % ['occurred', 5])
# prints: 'It occurred 5 times'
Code
s
c
d
u
H or h
f
E or e
G or g
%
'%s' %
'%f' %
'%
...
2e'
'%03d'
Meaning
String or string conversion
Character
Signed decimal integer
Unsigned decimal integer
Hex integer (upper or lower case)
Floating point
Exponent (upper or lower case E)
The shorter of e and f (u/l case)
Literal '%'
math
...
pi
% math
...
14159265359'
'3
...
14'
'3
...
format(arguments)
Examples (using similar codes as above):
'Hello {}'
...
format(math
...
14159265359'
'{0:
...
format(math
...
14'
'{0:+
...
format(5)
# '+5
...
2e}'
...
00e+03'
'{:0>2d}'
...
format(5)
# '5xx' (rt
...
format(1000000)
# '1,000,000'
'{:
...
format(0
...
0%'
'{0}{1}'
...
format('a', 'b') # 'ba'
'{num:}'
...
count(value)
first_occurrence = L
...
format(value)
List methods (not a complete list)
Method
What it does
l
...
extend(other)
Append items from other
l
...
remove(x)
Remove first occurrence of x; An
error if no x
l
...
index(x)
Get index of first occurrence of
x; An error if x not found
l
...
sort()
In place list sort
l
...
a = set()
# empty set
a = {'red', 'white', 'blue'} # simple set
a = set(x)
# convert list
Trap: {} creates empty dict, not an empty set
Set comprehensions
# a set of selected letters
...
s = {(x,y) for x in range(-1,2)
for y in range (-1,2)}
Trap: set contents need to be immutable to be
hashable
...
Iterating a set
for item in set:
print (item)
Searching a set
if item in set:
print (item)
if item not in set:
print ('{} is missing'
...
add(item)
Add item to set
s
...
Raise
KeyError if item not found
...
discard(item)
Remove item from set if present
...
pop()
Remove and return an arbitrary
item
...
s
...
copy()
Get shallow copy of set
s
...
issubset(o)
Same as set <= other
s
...
union(o[,
...
intersection(o)
Return new intersection
s
...
f = frozenset(s)
# convert set
f = frozenset(o)
# convert other
Dictionary (indexed, unordered map-container)
A mutable hash map of unique key=value pairs
...
split("=") for i in s
...
items() }
# next example -> count list occurrences
l = [1,2,9,2,7,3,7,1,22,1,7,7,22,22,9,0,9,0]
c = { key: l
...
items():
print (key, value)
Searching a dictionary
if key in dictionary:
print (key)
Merging two dictionaries
merged = dict_1
...
update(dict_2)
Dictionary methods (not a complete list)
Method
What it does
len(d)
Number of items in d
d[key]
Get value for key or raise the
KeyError exception
d[key] = value
Set key to value
del d[key]
deletion
key in d
True or False
key not in d
True or False
iter(d)
An iterator over the keys
d
...
copy()
Shallow copy of dictionary
d
...
items()
Dictionary's (k,v) pairs
d
...
pop(key[, def])
Get value else default; remove
key from dictionary
d
...
setdefault(k[,def]))
If k in dict return its value
otherwise set def
d
...
values()
The values from dict
Version 14 March 2015 - [Draft – Mark Graph – mark dot the dot graph at gmail dot com – @Mark_Graph on twitter]
4"
Key functions (not a complete list)
Function
What it does
abs(num)
Absolute value of num
all(iterable)
True if all are True
any(iterable)
True if any are True
bytearray(source)
A mutable array of bytes
callable(obj)
True if obj is callable
chr(int)
Character for ASCII int
complex(re[, im])
Create a complex number
divmod(a, b)
Get (quotient, remainder)
enumerate(seq)
Get an enumerate object, with
next() method returns an (index,
element) tuple
eval(string)
Evaluate an expression
filter(fn, iter)
Construct a list of elements from
iter for which fn() returns True
float(x)
Convert from int/string
getattr(obj, str)
Like obj
...
isinstance(2
...
repr(object)
Printable representation of an
object
reversed(seq)
Get a reversed iterator
round(n[,digits])
Round to number of digits after
the decimal place
setattr(obj,n,v)
Like obj
...
For example:
result = function(32, aVar, c='see', d={})
Arguments are passed by reference (ie
...
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
...
Expressions in default arguments are evaluated when
the function is defined, not when it’s called
...
def nasty(value=[]):
# <-- mutable arg
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
...
# 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
...
They are useful for avoiding hard constants
...
def derivative(f, dx):
"""Return a function that approximates
the derivative of f using an interval
of dx, which should be appropriately
small
...
00001)
f_dash_x(5) # yields approx
...
y'=2x)
Version 14 March 2015 - [Draft – Mark Graph – mark dot the dot graph at gmail dot com – @Mark_Graph on twitter]
5"
An iterable object
The contents of an iterable object can be selected one
at a time
...
An iterable object will produce
a fresh iterator with each call to iter()
...
With each loop, it calls
next() on the iterator until a StopIteration exception
...
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
...
Trap: a yield statement is not allowed in the try clause of
a try/finally construct
...
send(None) # !
print x
...
send(None) # !
print x
...
Methods and attributes
Most objects have associated functions or “methods”
that are called using dot syntax:
obj
...
attribute)
Simple example
import math
class Point:
# static class variable, point count
count = 0
def __init__(self, x, y):
self
...
y = float(y)
Point
...
format(self
...
y)
def to_polar(self):
r = math
...
x**2 + self
...
atan2(self
...
x)
return(r, theta)
# static method – trivial example
...
format(n))
static_eg = staticmethod(static_eg)
# Instantiate 9 points & get polar
for x in range(-1, 2):
for y in range(-1, 2):
p = Point(x, y)
print (p) # uses __str__()
print (p
...
count) # check static
Point
...
Usually named 'self'; it is a reference to the instance
...
Self is like 'this' in C++ & Java
Generator expressions
Generator expressions build generators, just like
building a list from a comprehension
...
[i for i in xrange(10)] # list comprehension
list(i for i in xrange(10)) # generated list
Public and private methods and variables
Python does not enforce the public v private data
distinction
...
Variables
that begin with double underscore are mangled by the
compiler (and hence more private)
...
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
...
Practically, decorators are syntactic sugar for more
readable code
...
For example, the following two method
definitions are semantically equivalent
...
):
...
):
...
class Example:
def __init__(self):
self
...
_x
def setx(self, value):
self
...
_x
x = property(getx, setx, delx,"Doc txt")
Which can be rewritten with decorators as:
class Example:
def __init__(self):
self
...
"""
return self
...
setter
def x(self, value):
self
...
deleter
def x(self):
del self
...
Magic method
What it does
__init__(self,[
...
Called by
str(self)
__repr__(self)
Machine readable
unambiguous Python
string expression for class
contents
...
__eq__(self, other)
Behaviour for ==
__ne__(self, other)
Behaviour for !=
__lt__(self, other)
Behaviour for <
__gt__(self, other)
Behaviour for >
__le__(self, other)
Behaviour for <=
__ge__(self, other)
Behaviour for >=
__add__(self, other)
Behaviour for +
__sub__(self, other)
Behaviour for __mul__(self, other)
Behaviour for *
__div__(self, other)
Behaviour for /
__mod__(self, other)
Behaviour for %
__pow__(self, other)
Behaviour for **
__pos__(self, other)
Behaviour for unary +
__neg__(self, other)
Behaviour for unary __hash__(self)
Returns an int when
hash() called
...
name = val
__getattribute__(self,
Called by self
...
name
name)
does not exist
__delattr__(self,
Called by
name)
del self
Title: Python Notes For Beginers
Description: By This Notes you can master python simple programas.This notes is made by reffering many books and experts made this out.check out this note will be very useful in your academics./
Description: By This Notes you can master python simple programas.This notes is made by reffering many books and experts made this out.check out this note will be very useful in your academics./