Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Hey Ninjas!! Welcome to an article on python power.
Python is, without a doubt, one of the most well-known and widely used programming languages available today. Python includes various functions, each created to increase the interface's adaptability. The Power operator in Python, often known as pow(), is a component of the Python ecosystem.
The article explains the details of the python power function. Let's get started.
When calculating the power of a variable to another, one can use the python power function. The Python Pow() function returns u to the power of v, modulus of z if the user adds the third variable z to the equation in a certain circumstance. This has a mathematical representation that is similar to pow(u, v)% z.
The syntax for the python power function:
pow(u, v[, z])
You can also try this code with Online Python Compiler
The Power operator in Python returns a number of distinct variables depending on the circumstance it is used in. The following list includes some of the more significant ones.
Example - 1
print(pow(4,2))
You can also try this code with Online Python Compiler
# positive u, positive v (u**v)
print(pow(3, 3))
# negative u, positive v
print(pow(-3, 3))
# positive u, negative v (u**-v)
print(pow(2, -2))
# negative u, negative v
print(pow(-2, -2))
You can also try this code with Online Python Compiler
We have three methods to find power without using the Power operator in Python.
Using loop
Using Recursion
Using bit masking
Using loop
Power can be calculated by repeatedly adding. For instance, to calculate 5^4.
Example
# Works only if both u and v>=0.
def pow(u,v):
if(v==0):
return 1
result=u
increment=u
for i in range(1,v):
for j in range (1,u):
result+=increment
increment=result
return result
print(pow(5,4))
You can also try this code with Online Python Compiler
def pow(u, v):
result = 1
while(v > 0):
# Determine the last bit of v.
last_bit = v&1
if(last_bit):
result = result*u
# Every subsequent bit was squared.
u = u*u
v = v >> 1
return result
print(pow(5, 4))
You can also try this code with Online Python Compiler
Base, exponent, and modulus are the inputs the built-in pow() function accepts; modulus is the third argument and is optional.
Why do we use the python power function?
The pow() function determines a number's power for every given value.
How do you write powers in Python?
In Python, you can write the power as 2**5 which means 2^5 and you can also use the pow function which takes 2 parameters, the base and the exponent that is pow(2, 5).
Conclusion
In this article, we have discussed the details of the python power function and Methods Power operator in Python.
We hope that the blog has helped you enhance your knowledge regarding the python power function.