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