In [20]:
a= "I'm a string"
def fibonnaci(n):
"""Will give you back the nth fibonnaci number, starting at 0"""
# Can put in triple-quoted string here as a doc-string which is used in help()
# Functions are indented
a, b = 0, 1
for i in range(n-1):
a, b = b, a+b
return a
help(fibonnaci)
print(fibonnaci(6)) # Call functions in the obvious way
print(a) # 'a' is unchanged by its doppleganger inside the function
In [1]:
a = 10
def global_change():
global a # Have to call 'global a' to gain access to 'a' so we can reassign it.
a = 20
def print_global():
print(a) # Can read access variables outside of function without calling global
global_change()
print_global()
In [12]:
def change_value(x):
print(id(x), end=" ") # Is it the same object?
x.pop() # remove the last element
a = list(range(6)) #Construct list
print(id(a),a) # Find out its id and contents
change_value(a) #Use function to change it in place with no copying
print(a)
In [22]:
def many_arguments(first_name, surname, country, dob="1979 01 01"):
return [first_name, surname, country, dob]
# Your default arguments must come last in the function definition
print(many_arguments("David", "Dossett", "UK", "1987 02 20"))
print(many_arguments("David", country="UK", surname="Dossett"))
In [4]:
# BE CAREFUL ABOUT USING MUTABLE TYPES AS DEFAULT ARGUMENTS!!!
def mutable_weird(x=[]):
x.append(1)
return x
print(mutable_weird())
print(mutable_weird())
print(mutable_weird())
print(mutable_weird([0])) #Passing in a list instead of using the default
# Can assign variable names to a function object
func = mutable_weird # Note the absence of brackets
print(func)
print(func())
def
keyword.
In [10]:
# lambda syntax; lambda arguments: expression
odds = list(filter( lambda x: x%2, range(10)))
print(odds)
# Filter() takes a function and an iterable as arguments and returns an iterator
# that can be used to create the list. Only elements that return True from the
# passed function will be used in the final list.
In [11]:
def f(x, y):
return x+y
g = lambda x, y: x+y # Equivalent lambda function bound to a variable
print(f(4,6), g(4,6)) # Called in the same way
return
the value of their expression.sorted()
, map()
, filter()
and reduce()
.