Problem No 14
Create a function factory returning customized functions
Medium≈ 15 minute session
Lesson guide
What this Python exercise practices
Create a function factory returning customized functions is a intermediate practice lesson that focuses on functions, parameters, return values. It is designed to be solved in about 15 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- Function parameters
- Return values
Difficulty and time
- Level
- Intermediate
- Estimated time
- 15 minutes
Practice path
Summary
Build a function factory that returns specialized functions capturing parameters from their creation scope.
Problem statement
Write a function make_power(exponent) that returns a new function. The returned function should accept a single numeric argument x and return x ** exponent. This demonstrates how a factory function captures and reuses configuration (exponent) via closures.
Task
Implement make_power(exponent) that returns a function which raises its input to the given exponent.
Examples
Square and cube factories
Input
make_power(2)(3)
Output
9
Explanation
make_power(2) returns a function that squares its input. Calling it with 3 returns 9.
Zero exponent
Input
make_power(0)(5)
Output
1
Explanation
Any non-zero number to the power 0 is 1.
Input format
Call make_power with a numeric exponent and immediately call the returned function with a numeric value, e.g., make_power(3)(2).
Output format
Return the numeric result of raising the input to the stored exponent (as Python would display it).
Constraints
- exponent may be any integer (positive, zero, negative). - The returned function should work with integers and floats. - Use closures to capture the exponent value.
Samples
Sample input 0
make_power(-1)(2)
Sample output 0
0.5
Explanation 0
A negative exponent inverts the base (2 ** -1 == 0.5).
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 per unlocked preview lesson.