pow()

The built-in pow() function computes the power of a given base raised to a specific exponent. It can also perform modular arithmetic more efficiently than using the power (**) and modulo (%) operators separately:

Python
>>> pow(2, 8)
256

>>> pow(2, 8, 5)
1

pow() Signature

Python Syntax
pow(base, exp, mod=None)

Arguments

Argument Description Default Value
base The base number to be raised to the power of exp. Required argument
exp The exponent to which the base is raised. Required argument
mod An optional modulus to compute the result modulo mod. None

Return Value

  • With integer or floating-point arguments, pow() returns the result of raising base to the power of exp.
  • If mod is provided, pow() returns the result of (base**exp) % mod, computed more efficiently.
  • If the exp is negative, and mod is present, pow() returns the modular inverse.

pow() Examples

With two integer arguments to compute a power:

Python
>>> pow(3, 4)
81

With two floating-point values:

Python
>>> pow(2.5, 8.2)
1832.7704375937353

With three arguments for modular exponentiation:

Python
>>> pow(3, 4, 5)
1

With a negative exponent and a modulus for computing the modular inverse:

Python
>>> pow(38, -1, 97)
23

pow() Common Use Cases

The most common use cases for the pow() function include:

  • Calculating powers of numbers.
  • Performing modular arithmetic efficiently.
  • Computing modular inverses in number theory.

pow() Real-World Example

Let’s say you’re implementing a simple encryption algorithm that requires modular exponentiation, which is a common operation in cryptography:

Python
>>> base = 5
>>> exp = 117
>>> mod = 19
>>> encrypted = pow(base, exp, mod)
>>> encrypted
1

In this example, pow() computes the encrypted value efficiently, which is vital for the encryption and decryption processes.

Tutorial

Python's Built-in Functions: A Complete Exploration

In this tutorial, you'll learn the basics of working with Python's numerous built-in functions. You'll explore how to use these predefined functions to perform common tasks and operations, such as mathematical calculations, data type conversions, and string manipulations.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 22, 2024 • Reviewed by Dan Bader