Python Program to Compute the Power of a Number
|In this Python example, we will explore some ways to calculate the power of a number.
1. What do you mean by the Power of a Number?
Calculating the power of a number means finding the value obtained by multiplying the number by itself a certain number of times.
Example: Input : 2 to the power of 3 Output : 8 2 x 2 x 2
Some of the topics which will be helpful for understanding the program implementation better are:
2. Using “**” method
computing the power of a number is an easy task with the use of the “**” operator. This operator takes two operands, the base, and the exponent, and returns the result of raising the base to the power of the exponent.
base = int(input("Enter the base number: ")) exponent = int(input("Enter the exponent: ")) result = base ** exponent print("{} to the power of {} is {}".format(base, exponent, result))
Output Enter the base number: 2 Enter the exponent: 3 2 to the power of 3 is 8
3. Using pow() function
One way is to use the built-in pow
function. This function takes two arguments, the base number and the exponent, and returns the result of raising the base to the exponent.
Here’s an example:
base = int(input("Enter the base number: ")) exponent = int(input("Enter the exponent: ")) result = pow(base, exponent) print("{} to the power of {} is {}".format(base, exponent, result))
Output Enter the base number: 2 Enter the exponent: 3 2 to the power of 3 is 8
3. Using for loop method
The values() method returns a view object that contains the values of the dictionary. We can loop over this view object using for loop to access the values.
def power(base, exponent): result = 1 for i in range(exponent): result *= base return result base = int(input("Enter the base number: ")) exponent = int(input("Enter the exponent: ")) result = power(base, exponent) print("{} to the power of {} is {}".format(base, exponent, result))
Output Enter the base number: 2 Enter the exponent: 3 2 to the power of 3 is 8
4. Conclusion
This article exhibits multiple ways to calculate the power of a number in Python.
Helpful Links
Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.
Also for examples in Python and practice please refer to Python Examples.
Complete code samples are present on Github project.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?