In this post, you will learn a Python Program to Find the Power of a number without using the pow function with a simple explanation.
There are various ways to find the power of a number without using the pow() function but here we learn the three best ways to do it.
So let us start writing programs using all three ways one by one.
Using Arithmetic Operator
Before writing a program you should know about:
- Arithmetic Operators { Exponential (
**
) }
Source code
base = int(input('ENter base value: '))
exponent = int(input('ENter exponent value: '))
ans = base**exponent
print(f'Answer is : {ans}')
Output
ENter base value: 3
ENter exponent value: 2
Answer is : 9
Using for-loop
Before writing a program you should know about:
Source Code
base = int(input('ENter base value: '))
exponent = int(input('ENter exponent value: '))
ans = 1
for i in range(exponent):
ans *= base
print(f'Answer is : {ans}')
Output
ENter base value: 3
ENter exponent value: 4
Answer is : 81
Using Function
This is a new way to do this program and it also helps you to understand the concepts of Python Functions.
Before writing a program few programming concepts you have to know:
- Python Function &
- you are familiar with the concept of Function return a function.
- Arithmetic Operators { Exponential (
**
) }
Source Code
def to_power(x):
def num(n):
return n**x
return num
base = int(input('ENter base value: '))
exponent = int(input('ENter exponent value: '))
result = to_power(exponent)
print(f'Answer is : {result(base)}')
Output
ENter base value: 16
ENter exponent value: 2
Answer is : 256
Instead of Using a concept of function return function, you can directly write:
def to_power(n,x):
return n**x
print(to_power(2,3))
Output: 8