Partial Function in Python

Level 4165 keystrokes

This creates partial functions with pre-filled arguments. The partial() function fixes some arguments of a function.

Python code

# Import partial from functools module
1from functools import partial
2
# Define a function that calculates power
3def power(base, exp):
# Return base raised to exponent
4 return base ** exp
5
# Create partial function with exp fixed to 2
6square = partial(power, exp=2)
# Create partial function with exp fixed to 3
7cube = partial(power, exp=3)
8
# Call square(5) which is power(5, exp=2) = 25
9print(square(5))
# Call cube(3) which is power(3, exp=3) = 27
10print(cube(3))

Output

25
27
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • (× 7
  • )× 7
  • =× 4
  • ,× 3
  • *× 2
  • :× 1

More Python examples at level 4

← Python typing practice