Python Program - Power of a Number
If power (or exponential) of number indicates how many the number is multiplied by itself to get the final number. For example:
x raised to the power 2 = x² = x*x
x raised to the power 3 = x³ = x*x*x
Method 1: Using conditional statement
In the example below, a function called Power() is created to calculate power of a number. It uses while loop to achieve this. This method can be used to calculate the power of a number where power should be a non-negative integer.
def Power(x, n): finalnum = 1 n1 = n while(n1 > 0): finalnum = finalnum * x n1 = n1 - 1 print(x, "raised to the power", n, "=", finalnum) Power(3, 5) Power(5, 0) Power(6, 2)
The above code will give the following output:
3 raised to the power 5 = 243 5 raised to the power 0 = 1 6 raised to the power 2 = 36
Method 2: Using exponential (**) operator
The exponential (**) operator of Python can be used to calculate the power of a number. See the example below for syntax. It can be used to calculate xn for any value of n (n can be negative or fraction).
x, y, z = 3, 5, 6 a, b, c = 5, 0, 2 print(x, "raised to the power", a, "=", x**a) print(y, "raised to the power", b, "=", y**b) print(z, "raised to the power", c, "=", z**c)
The above code will give the following output:
3 raised to the power 5 = 243 5 raised to the power 0 = 1 6 raised to the power 2 = 36
Method 3: Using pow() method of math Module
The pow() method of math module can also be used to calculate power of a number. It can be used to calculate xn for any value of n (n can be negative or fraction).
import math x, y, z = 3, 5, 6 a, b, c = 5, 0, 2 print(x, "raised to the power", a, "=", math.pow(x,a)) print(y, "raised to the power", b, "=", math.pow(y,b)) print(z, "raised to the power", c, "=", math.pow(z,c))
The above code will give the following output:
3 raised to the power 5 = 243 5 raised to the power 0 = 1 6 raised to the power 2 = 36
Recommended Pages
- Python Program - To Check Prime Number
- Python Program - Bubble Sort
- Python Program - Selection Sort
- Python Program - Maximum Subarray Sum
- Python Program - Reverse digits of a given Integer
- Python - Swap two numbers
- Python Program - Fibonacci Sequence
- Python Program - Insertion Sort
- Python Program - Find Factorial of a Number
- Python Program - Find HCF of Two Numbers
- Python Program - Merge Sort
- Python Program - Shell Sort
- Stack in Python
- Queue in Python
- Python Program - Find LCM of Two Numbers
- Python Program - To Check Armstrong Number
- Python Program - Counting Sort
- Python Program - Radix Sort
- Python Program - Find Largest Number among Three Numbers
- Python Program - Print Floyd's Triangle