In this python tutorial, you will learn how to calculate the power using Recursion with the if, else, elif statements and operators of the python programming language.
How to calculate the power using recursion?
Let’s take a look at the source code, here the values are given as input by the user in the code, the if, else, elif statements and operators carry out the function.RUN CODE SNIPPET
#Python program to calculate the power using recursion def power(N, P): if P == 0: return 1 elif P == 1: return N else: return (N*power(N, P-1)) N = int(input("Enter the first integer: ")) P = int(input("\nEnter the second integer: ")) print("\nThe power is : ",end="") print(power(N, P))
Enter the first integer: Enter the second integer: The power is : 36
- At the start, we use
def power(N, P)where the
defkeyword is used to define a function and the
power(N, P)is to call the power function to get the value of
- We declare an
ifstatement with the condition
P == 0, where if the condition is satisfied, will return the value of
1using the return function, if it is not satisfied, it moves to the next step, which is the
- We declare the
elifstatement with the condition
P == 1, where if the condition is satisified, will return the value of
Nusing the return function, if it is not satisfied, it moves to the next step, which is the
- In the
elsestatement, its returns the value of the condition
(N*power(N, P-1)), where the value of
Nis multiplied with itself , according to the value of
- Here we give the user the option to enter the values where we declare a
("Enter the first integer: ")and
("Enter the second integer: "), the input values are scanned using the
inputfunction and are stored in the variables
P,we use the
intfunction and declare the input value as an integer value.
- We use another
- The input() function allows a user to insert a value into a program, it returns a string value.
- The if and else statements evaluates whether an expression is true or false. If a condition is true, the “if” statement is executed otherwise, the “else” statement is executed.
- The colon : at the end of the if and else statement tells Python that the next line of code should only be run if the condition is true.
- The elif is short for else if, it allows us to check for multiple expressions.
- The statement for the input function are enclosed in single quotes and parenthesis.
- The \n in the code indicates a new line or the end of a statement line or a string.
- The print statement/string to be displayed in enclosed in double quotes.