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:
>>> pow(2, 8) 256 >>> pow(2, 8, 5) 1 pow() Signature
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 raisingbaseto the power ofexp. - If
modis provided,pow()returns the result of(base**exp) % mod, computed more efficiently. - When
expis negative andmodis present,pow()returns the modular inverse.
pow() Examples
With two integer arguments to compute a power:
>>> pow(3, 4) 81 With two floating-point values:
>>> pow(2.5, 8.2) 1832.7704375937353 With three arguments for modular exponentiation:
>>> pow(3, 4, 5) 1 With a negative exponent and a modulus for computing the modular inverse:
>>> 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
Say you’re implementing a simple encryption algorithm that requires modular exponentiation, which is a common operation in cryptography:
>>> 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.
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Numbers in Python (Tutorial)
- Python's Built-in Functions: A Complete Exploration (Quiz)