Code Explanation:
1. Importing partial
from functools import partial
- The functools module provides tools for working with functions.
- partial() allows you to create a new function by fixing one or more arguments of an existing function.
- This helps reuse a function without repeatedly passing the same argument.
2. Defining the power() Function
def power(x, n):
- The def keyword defines a function named power.
- It accepts two parameters: x and n.
- x represents the base, while n represents the exponent.
3. Calculating the Power
return x ** n
- The ** operator performs exponentiation.
- It raises x to the power of n.
- For example, power(2, 3) returns 8 because \(2^3 = 8\).
4. Creating the square() Function
square = partial(power, n=2)
- partial() creates a new function based on power().
- The argument n=2 is fixed.
- Now, calling square(4) is equivalent to calling power(4, 2).
- The result is \(4^2 = 16\).
5. Creating the cube() Function
cube = partial(power, n=3)
- This creates another function with n=3 fixed.
- Calling cube(2) is equivalent to calling power(2, 3).
- The result is \(2^3 = 8\).
6. Printing the Results
print(square(4), cube(2))
- square(4) returns 16.
- cube(2) returns 8.
- The print() function displays both values separated by a space.
Final Output
16 8
Book: 100 Python Programs for Beginner with explanation


0 Comments:
Post a Comment