Nested Functions
Files associated with this lesson:
Nested Functions.ipynb
Nested Functions¶
In [4]:
def calculate(op, x, y):
def add():
return x + y
def subtract():
return x - y
def multiply():
return x * y
def divide():
return x / y
if op == 'add':
return add()
elif op == 'subtract':
return subtract()
elif op == 'multiply':
return multiply()
else:
return divide()
In [5]:
calculate('divide', 2, 3)
In [3]:
calculate('add', 2, 3)
Out[3]:
nonlocal
(Python 3 only)¶
In [7]:
result = 'Something completely unrelated'
def calculate(op, x, y):
result = 'not changed'
def add():
nonlocal result
result = x + y
def subtract():
result = x - y
def multiply():
result = x * y
def divide():
result = x / y
if op == 'add':
add()
elif op == 'subtract':
subtract()
elif op == 'multiply':
multiply()
else:
divide()
return result
print("Calc result: ", calculate('add', 2, 3))
print("Global result: ", result)
In [ ]:
calculate('add', 2, 3)
In [ ]: