Lesson guide
What this Python exercise practices
Build an Adder Function Factory is a beginner practice lesson that focuses on functions, parameters, return values. It is designed to be solved in about 8 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- Function parameters
- Return values
Difficulty and time
- Level
- Beginner
- Estimated time
- 8 minutes
Related public exercises
Summary
Create a closure that captures a value and returns a function which adds that value to its input.
Problem statement
Write a function factory make_adder(n) that returns a new function. The returned function should accept a single numeric argument x and return x + n. The returned function must capture the value n from the enclosing scope so it continues to add n even after make_adder has returned. Do not use global variables.
Task
Implement make_adder(n) which returns a function that adds n to its argument, demonstrating how closures capture variables from an enclosing scope.
Examples
Basic usage
Input
make_adder(2)(3)
Output
5
Explanation
make_adder(2) returns a function that adds 2. Calling it with 3 returns 3 + 2 = 5.
Input format
A single expression calling make_adder with an integer/float and then calling the returned function with a numeric argument, e.g., make_adder(5)(3).
Output format
Return the numeric result of adding the captured value to the argument. The test harness compares the string form of the return value.
Constraints
- You must implement make_adder as a closure (inner function capturing n). - Do not use global variables. - Support integers (and floats) as inputs.
Samples
Sample input 0
make_adder(0)(10)
Sample output 0
10
Explanation 0
Adding 0 returns the original value.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.