Functions Object-Oriented Exception Handling
Python is pass by reference, function arguments • Application :
Programming 1. Basic Form :
are passed by reference. 1. 'object' is the root of all Python types try:
sorted(set('abc bcd')) => [' ', ..
• Basic Form : 'a', 'b', 'c', 'd'] 2. Everything (number, string, function, class, module, except ValueError as e:
# returns sorted unique characters etc.) is an object, each object has a 'type'. Object print e
def func1(posArg1, keywordArg1 = variable is a pointer to its location in memory.
1, ..): except (TypeError, AnotherError):
3. Zip pairs up elements of a number of lists, tuples or ..
3. All objects are reference-counted. except:
other sequences to create a list of tuples : ..
Note : sys.getrefcount(5) => x
zip(seq1, seq2) => finally:
• Keyword arguments MUST follow positional a = 5, b = a .. # clean up, e.g. close db
arguments. [('seq1_1', 'seq2_1'), (..), ..]
# This creates a 'reference' to the object on the
• Python by default is NOT "lazy evaluation", right side of =, thus both a and b point to 5 2. Raise Exception Manually
expressions are evaluated immediately. • Zip can take arbitrary number of sequences.
However, the number of elements it produces is raise AssertionError # assertion failed
sys.getrefcount(5) => x + 2 raise SystemExit # request program exit
• Function Call Mechanism : determined by the 'shortest' sequence.
del(a); sys.getrefcount(5) => x + 1 raise RuntimeError('Error message :
1. All functions are local to the module level • Application : Simultaneously iterating over multiple ..')
scope. See 'Module' section. sequences : 4. Class Basic Form :
2. Internally, arguments are packed into a tuple for i, (a, b) in
List, Set and Dict
class MyObject(object):
and dict, function receives a tuple 'args' and enumerate(zip(seq1, seq2)): # 'self' is equivalent of 'this' in Java/C++
dict 'kwargs' and internally unpack.
• Common usage of 'Functions are objects' : • Unzip - another way to think about this is
converting a list of rows to a list of columns.
def __init__(self, name):
self.name = name
Comprehansions
def func1(ops = [str.strip, user_ def memberFunc1(self, arg1): Syntactic sugar that makes code easier to read and write
define_func, ..], ..): seq1, seq2 = zip(*zipOutput)
for function in ops: .. 1. List comprehensions
value = function(value) @staticmethod
4. Reversed iterates over the elements of a sequence • Concisely form a new list by filtering the elements
def classFunc2(arg1): of a collection and transforming the elements
RETURN VALUES in reverse order. passing the filter in one concise expression.
..
• None is returned if end of function is reached list(reversed(range(10))) * obj1 = MyObject('name1') • Basic form :
without encountering a return statement. obj1.memberFunc1('a')
[expr for val in collection if condition]
• Multiple values return via ONE tuple object * reversed() returns the iterator, list() makes MyObject.classFunc2('b')
it a list. A shortcut for :
return (value1, value2) 5. Useful interactive tool : result = []
value1, value2 = func1(..)
dir(variable1) # list all methods available on for val in collection:
ANONYMOUS (AKA LAMBDA) FUNCTIONS Control and Flow the object if condition:
result.append(expr)
• What is Anonymous function?
A simple function consisting of a single statement. 1. Operators for conditions in 'if else' : The filter condition can be omitted, leaving only the
lambda x : x * 2 Check if two variables are
Common String expression.
var1 is var2 2. Dict Comprehension
# def func1(x) : return x * 2 same object operations • Basic form :
. . . are different object var1 is not var2
• Application of lambda functions : 'curring' aka Concatenate ', '.join([ 'v1', 'v2', {key-expr : value-expr for value in
Check if two variables have var1 == var2
deriving new functions from existing ones by same value List/Tuple with 'v3']) => 'v1, v2, v3' collection if condition}
partial argument application. Separator
3. Set Comprehension
WARNING : Use 'and', 'or', 'not' operators for string1 = 'My name is {0}
ma60 = lambda x : pd.rolling_mean(x, {name}' • Basic form : same as List Comprehension except
60) compound conditions, not &&, ||, !. with curly braces instead of []
Format String newString1 = string1.
2. Common usage of 'for' operator : format('Sean', name = 4. Nested list Comprehensions
USEFUL FUNCTIONS (FOR DATA STRUCTURES) 'Chen')
Iterating over a collection (i.e. list for element in • Basic form :
1. Enumerate returns a sequence (i, value) tuples or tuple) or an iterator iterator : sep = '-';
where i is the index of current item. . . . If elements are sequences, for a, b, c in
Split String stringList1 = [expr for val in collection for
can be 'unpack' iterator : string1.split(sep) innerVal in val if condition]
for i, value in enumerate(collection):
3. 'pass' - no-op statement. Used in blocks where no
• Application : Create a dict mapping of value action is to be taken.
Get Substring start = 1; string1[start:8]
of a sequence (assumed to be unique) to their 4. Ternary Expression - aka less verbose 'if else' Created by Arianne Colton and Sean Chen
locations in the sequence. [email protected]
• Basic Form : month = '5';
2. Sorted returns a new sorted list from any sequence value = true-expr if condition String Padding month.zfill(2) => '05' Based on content from
else false-expr with Zeros month = '12'; 'Python for Data Analysis' by Wes McKinney
sorted([2, 1, 3]) => [1, 2, 3]
month.zfill(2) => '12'
5. No switch/case statement, use if/elif instead. Updated: May 3, 2016