undefined

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Functions - Part II

Here are a few more examples of functions in Python:

# Example: nested functions - variable scope (erroneous)
# calling create_accumulator fails with the following error message:
# "local variable 'tally' referenced before assignment"
def create_accumulator(seed=0):
tally = seed
def accumulate(x):
tally += x # local to accumulate(x)
return tally
return accumulate
# Example: nested functions - variable scope (the nonlocal statement)
def create_accumulator(seed=0):
tally = seed
def accumulate(x):
nonlocal tally # the fix
tally += x
return tally
return accumulate
accumulate = create_accumulator()
print(accumulate(2))
print(accumulate(3))
print(accumulate(5))
# Example: the global statement
tally = 0
def accumulate(x):
global tally
tally += x
return tally
print(accumulate(2))
print(accumulate(3))
print(accumulate(5))
# Example: returning multiple objects
def foo(x, y):
return x + y, x - y
a, b = foo(1, 2) # unpack the returned tuple into a and b
print(a)
print(b)
# Example: a variadic function
# the syntax *lines makes this function variadic
def print_lines(prefix, *lines):
for line in lines:
print(prefix, line)
# call the function with varargs
print_lines('[varargs example]', 'hello', 'world')
# Example: an equivalent to the example above
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content