Skip to content

Instantly share code, notes, and snippets.

@ldong
Last active August 29, 2015 14:02
Show Gist options
  • Save ldong/4625014e5d3d91365739 to your computer and use it in GitHub Desktop.
Save ldong/4625014e5d3d91365739 to your computer and use it in GitHub Desktop.

##Day 2 Agenda

Author: Rick Copeland

Date: June 17, 2014

Session 3, the second half

Functions in Python

Functions

positional arguments

def func(a, b):
  pritn a, b
  
func('foo', 'bar')      # order matters
func(b='foo', a='bar')  # order wont matter

lambda functions

lambda_addr = lambda a, b : a+b
lambda_addr(1, 2)

One line and one expressions, very similar to anonymous function in JavaScript.

Be careful when uses default argument

Rule of Thumb: never uses mutable default argument.

Side notes:

Python name spaces:

1. module level name space

2. function level name space

tuple

pack: *pack = a, b

unpack: a, b = *pack

i.e.

def func(name, *args):
	return sum(args)

dict

i.e.

def func(**kwargs):
	return kwargs
ret = func(a=1, b=2)

Advanced Functions

Recursive functions

def rec(first, *rest):
	print first, rest
	if rest:
		return rec(rest[0], rest[1:])
	else:
		return first
rec(1,2,3)

map, filter

  1. pre_order

  2. in_order

  3. post_order

Closures and lexical scoping

i.e.

def make_adder(val):
	def adder(other_val):
		return val + other_val
	return adder
add5 = make_adder(5)
add5(10)

Standard Library: Logging module

See you next time

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment