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))
INPUT:
6 2
OUTPUT:
Enter the first integer: Enter the second integer: The power is : 36
- At the start, we use
def power(N, P)
where thedef
keyword is used to define a function and thepower(N, P)
is to call the power function to get the value of(N, P)
- We declare an
if
statement with the conditionP == 0
, where if the condition is satisfied, will return the value of1
using the return function, if it is not satisfied, it moves to the next step, which is theelif
statement. - We declare the
elif
statement with the conditionP == 1
, where if the condition is satisified, will return the value ofN
using the return function, if it is not satisfied, it moves to the next step, which is theelse
statement. - In the
else
statement, its returns the value of the condition(N*power(N, P-1))
, where the value ofN
is multiplied with itself , according to the value ofP
. - Here we give the user the option to enter the values where we declare a
print
function which will display the statements("Enter the first integer: ")
and("Enter the second integer: ")
, the input values are scanned using theinput
function and are stored in the variablesN
andP,
we use theint
function and declare the input value as an integer value. - We use another
print
function to display the final value stored in the variables(power(N,P))
NOTE:
- 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.