0
0
Pythonprogramming~15 mins

Enclosing scope in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Enclosing Scope with Nested Functions
๐Ÿ“– Scenario: Imagine you are creating a simple calculator that can add a fixed number to any input number. You want to keep the fixed number hidden inside the calculator so it cannot be changed directly.
๐ŸŽฏ Goal: Build a nested function where the inner function uses a number from the outer function's scope (enclosing scope) to add to its input.
๐Ÿ“‹ What You'll Learn
Create an outer function called make_adder that takes one parameter fixed_number.
Inside make_adder, define an inner function called adder that takes one parameter num.
The inner function adder should return the sum of num and fixed_number from the enclosing scope.
The outer function make_adder should return the inner function adder.
Create a variable add_five by calling make_adder(5).
Call add_five(10) and print the result.
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
Enclosing scope is used in real-world programming to create functions that remember settings or data without using global variables.
๐Ÿ’ผ Career
Understanding enclosing scope helps in writing clean, reusable code and is important for jobs involving Python programming, especially in web development and data science.
Progress0 / 4 steps
1
Create the outer function make_adder with parameter fixed_number
Write a function called make_adder that takes one parameter called fixed_number. Inside it, define an inner function called adder that takes one parameter called num. Do not write the inner function body yet.
Python
Need a hint?

Remember to indent the inner function adder inside make_adder.

2
Make the inner function adder return the sum of num and fixed_number
Inside the inner function adder, write a return statement that adds num and fixed_number from the enclosing scope.
Python
Need a hint?

Use return num + fixed_number to add the inner parameter and the outer parameter.

3
Make make_adder return the inner function adder
Add a return statement at the end of make_adder that returns the inner function adder (without calling it).
Python
Need a hint?

Return the inner function adder itself, not the result of calling it.

4
Create add_five and print the result of add_five(10)
Create a variable called add_five by calling make_adder(5). Then call add_five(10) and print the result.
Python
Need a hint?

Calling add_five(10) should add 5 to 10 and print 15.