Python pow() Function



The built-in pow() function in Python is used to calculate the power of a number. It takes two required arguments: the base number (which is the number you want to raise to a power) and the exponent (which is the power to which the base is raised). Additionally, it accepts an optional third argument, mod, for performing modular arithmetic. The function returns the result of raising the base to the power of the exponent, optionally modulo mod.

You can use the pow() function with various data types, including integers, floating-point numbers, and even complex numbers. It is available without importing any additional modules.

In addition to the built-in pow() function in Python, the math module provides a method named math.pow(). While both calculate powers, the difference lies in the data types they handle and the types of results they return.

Syntax

Following is the syntax of Python built-in pow() function −

pow(x, y, mod =1)

Parameters

Following are the parameters accepted by the Python built-in pow() function −

  • x − numeric operand to be used as base.

  • y − numeric operand to be used as index.

  • mod − numeric operand to be used as denominator for mod calculation.

Return Value

This method returns the value of xy modulus z, if the third argument 'z' is specified.

Example

In the following example, we are we are calculating 23 using the built-in pow() function −

x = 2
y = 3
result = pow(x,y)
print ("Result:", result)

Output

It will produce the following output −

Result: 8

Example

The modulus parameter retrieves pow(base, exp) % mod result.

In the example given below, we have raised the number 7 to the power 4 which results in 2401. Since we have used the pow() method with three arguments a, b, and c, the third argument 8 divides the result of 2401 and finds the remainder. The value obtained is rounded off to its nearest integer −

a = 7
b = 4
c = 8
res = pow(a,b,c)
print('The result is:', res)

Output

While executing the above code, we get the following output −

The result is: 1

Example

In here, we are creating the base consisting of complex number. Then, we use the pow() method to retrieve the result −

# Creating the base
b = 5 + 9j
# Creating the exponent
exp = 3
# Printing the result 
result = pow(b, exp)
print("The result is:", result)

Output

Following is the output of the above code −

The result is: (-1090-54j)

Example

If we pass 3 arguments to this method, we encounter a "TypeError" while using a complex number or a float value as any of the three arguments. This specifies that all the 3 arguments has to be integers −

a = 7
b = 4
c = 8.2
res = pow(a,b,c)
print('The result is:', res)

Output

Output of the above code is as follows −

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 4, in <module>
    res = pow(a,b,c)
TypeError: pow() 3rd argument not allowed unless all arguments are integers
python_built_in_functions.htm
Advertisements