Power of a number using recursion in Python
In this post, you will learn how to write a Python program to get the power of a number using a recursion function.
A recursion function is a function that is called by itself. In the given example, we use the recursion function to get the power of a number. A recursion function continues until some condition is met to prevent it. That's why we use the if else statement to break the infinite recursion.
The following Python program calculates the base power exponent using a recursive function. In this program, we read the value of base and exponent from the user using the input() function, and then we calculate baseexponent using a recursive function power_num(). The base condition is given that if the exponential power is equal to 1, the base number is returned. If the exponential power isn't equal to 1, the base number multiplied with the power function is called recursively with the arguments as the base and power minus 1.
# Python power of a number using recursion
# Recursive function
def power_num(x,num):
# if power is 0 then return 1
if num==0:
return 1
# if power is 1 then number is
# returned
elif num==1:
return(x)
else:
return x * power_num(x, num-1)
# Reading inputs base and exponent
base = float(input("Enter value of base: "))
exponent = int(input("Enter value of exponent: "))
# Function call
result = power_num(base, exponent)
# Displaying output
print("Output : ", result)
Output of the above code -
Enter value of base: 4
Enter value of exponent: 3
Output : 64.0
Enter value of base: 4
Enter value of exponent: 0
Output : 1
Enter value of base: 5
Enter value of exponent: 1
Output : 5.0
Related Articles
zip function in Python
Fibonacci series in Python with recursion
Factorial using recursion in Python
Permutation of string in Python
Count consonants in a string Python
Reverse pyramid pattern in Python
Fizzbuzz program in Python
Python split string by comma
Python alive progress bar
Python progress bar tqdm
Python language translator code
Python take screenshot of specific window
Web scraping Python BeautifulSoup
Reverse a number in Javascript
HTML open link in new tab
Python print without newline
Python iterate list with index
Python add list to list
Python random choice
Python dict inside list
Remove character from string Python
Python raise keyword