The pow() function in Python is a built-in function that allows you to calculate the power of a number. In other words, it raises a given number to a given power. In this article, we will discuss the syntax of the pow() function, how to use it in Python, and provide examples of when to use it.
But, before we get to the content, we would like to inform you about our upcoming Python webinar. You can learn more about the Python functions and know beyond the basics of Python, in our upcoming Python Webinar. Keep watching our social media, especially our Instagram page. We will reveal the date soon.
The syntax of the pow() function is as follows:
pow(x, y, z=None)
Where:
x: the base value (mandatory argument)
y: the exponent value (mandatory argument)
z: an optional argument representing the modulus value (if present, it should be an integer)
Note that if the z argument is not present, the function returns x to the power of y. If z is present, then the function returns (x ** y) % z.
Example 1: Calculate the power of a number
Suppose you want to calculate 3 raised to the power of 2. You can use the pow() function as follows:
result = pow(3, 2)
print(result) # Output: 9
Example 2: Calculate the power of a number with modulus
Suppose you want to calculate 3 raised to the power of 2, modulo 5. You can use the pow() function as follows:
result = pow(3, 2, 5)
print(result) # Output: 4
In this example, 3 raised to the power of 2 is 9. But since we specified the modulus value as 5, the result is 4 (which is the remainder when 9 is divided by 5).
The pow() function can be used in a variety of situations, such as:
# Calculate the power of 2 to the 4th
result = pow(2, 4)
print(result) # Output: 16
# Calculate the remainder of 2 to the 4th divided by 7
result = pow(2, 4, 7)
print(result) # Output: 2
# Calculate 2 to the power of 4 modulo 7
result = pow(2, 4, 7)
print(result) # Output: 2
Conclusion
The pow() function in Python is a powerful tool that allows you to calculate the power of a number and perform modular exponentiation. With the help of the examples in this article, you should now have a good understanding of how to use this function in your own Python code.
Or if you wish to, you could pre-register for our simulation-based Python program on keySkillset.
Start learning new skills with the help of KeySkillset courses and our learning management system today!