1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# 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')
Enter to Rename, Shift+Enter to Preview