Python Program to Find Power of a Number
You can find the power of a number in Python using the
** operator like result = base ** exponent.Examples
Inputbase=2, exponent=3
Output8
Inputbase=5, exponent=0
Output1
Inputbase=3, exponent=4
Output81
How to Think About It
To find the power of a number, think of multiplying the base number by itself as many times as the exponent says. For example, 2 to the power 3 means 2 × 2 × 2. In Python, you can use the
** operator to do this easily.Algorithm
1
Get the base number from the user or input.2
Get the exponent number from the user or input.3
Calculate the power by multiplying the base by itself exponent times or use the <code>**</code> operator.4
Return or print the result.Code
python
base = 2 exponent = 3 result = base ** exponent print(result)
Output
8
Dry Run
Let's trace the example where base=2 and exponent=3 through the code.
1
Assign base
base = 2
2
Assign exponent
exponent = 3
3
Calculate power
result = 2 ** 3 = 8
4
Print result
Output: 8
| Step | Operation | Value |
|---|---|---|
| 1 | base assigned | 2 |
| 2 | exponent assigned | 3 |
| 3 | power calculated | 8 |
| 4 | result printed | 8 |
Why This Works
Step 1: Using the ** operator
The ** operator in Python raises the base to the power of the exponent, performing repeated multiplication internally.
Step 2: Assigning values
We assign the base and exponent to variables so the code can use them to calculate the power.
Step 3: Printing the result
The print() function outputs the final calculated power to the screen.
Alternative Approaches
Using pow() function
python
base = 2 exponent = 3 result = pow(base, exponent) print(result)
The built-in <code>pow()</code> function does the same calculation and can be clearer for beginners.
Using a loop to multiply
python
base = 2 exponent = 3 result = 1 for _ in range(exponent): result *= base print(result)
This manual method shows how repeated multiplication works but is longer and less efficient.
Complexity: O(1) time, O(1) space
Time Complexity
Using the ** operator or pow() function is done in constant time because Python handles the calculation internally.
Space Complexity
The calculation uses a fixed amount of memory regardless of input size, so space complexity is constant.
Which Approach is Fastest?
The ** operator and pow() function are fastest and most readable; using a loop is slower and more verbose.
| Approach | Time | Space | Best For |
|---|---|---|---|
| ** operator | O(1) | O(1) | Simple and fast power calculation |
| pow() function | O(1) | O(1) | Clear built-in function usage |
| Loop multiplication | O(n) | O(1) | Understanding repeated multiplication |
Use the
** operator for a simple and fast way to calculate powers in Python.Beginners often forget that any number to the power 0 is 1, so they might get wrong results for exponent 0.