basic structure
def myname_of_function(arg1,arg2):
return arg1 + arg2default an argument
def my_function(name = ‘Default’):
indefinite arguments in a func
def myfunc(*args):
print(args)args return back a tuple
key word argument
def myfunc(**kwargs):
if 'fruit' in kwargs:myfunc(fruit = ‘apple’, veggie = ‘lettuce’)
kwargs return back a dictionary
map function
map( function ***no parenthesis, iterables)
map will apply the function into each iterables
filter function
filter down an iterables. function has to return boolean
lambda expressions
a function only use one time and will not be called again, without the def or a function name
lambda num:num**2
usually use together with map / filter
LEGB rule
local: within in function
-> Enclosing function local ->
global -> built-in
global assignment in a function
func():
global x
x=50 --> affect globallytry to avoid using global
passing function in function
function is first class object
def a(x):
return "a(%s)" % (x,)def b(f,x):
return f(x)print b(a,10)
what is a Generator?
Generator can send back a value and then later resume to pick up where it left off.
thus generate a sequence of values over time instead of storing all of the values in memory
range is a type of generator
it’s all about memory efficient in a for loop.
to see all the values, cast it to a list
how to operate generator
next and iter
g = simple_gen()
print(next(g))
print(next(g))
iter turn something iterable into a generator
generator comprehension
mylist = [1,2,3,4,5]
gencomp = (x for x in mylist if x > 3)
g = gencomp
note that a generator object is different from a generator function
Decorator
@new_decor
def func_needs_decorator():
print("I want to be decorated!!")this pass the func_needs_decorator() into a wrapper function “new_decor”. the @ line act as an on/off
function can return function, after assignment it can be called
passing a function as an argument
def other(wahtevername):
print("something")
print(whatevername())