Python program to calculate the power using ‘while-loop’

In this tutorial, we are going to learn a python program to calculate the power of a given number without using inbuild python pow function.

Problem Statement

For any two numbers that are inputs given by the user, one is the base value let’s say it as ‘x’ and the other is the exponent let’s say it as ‘y’, we have to print xy.

 For example:

Case1: If the user inputs the base of the number as 2 and exponent as 3

                        then the output should be ‘8’.

Case2: If the user inputs the base of the number as 5 and exponent as 2.

            then the output should be ‘25’.

While Loop

While Loop in python is used to repeatedly execute a block of statements until a given condition is satisfied. And when the condition becomes false, the block after the loop in the program is executed. While loop falls under the category of indefinite iteration. Indefinite iteration means that the number of times the loop is executed isn’t specified explicitly in advance. 

Statements represent all the statements indented by the same number of character spaces after a programming construct are considered part of a single block of code. Python uses indentation as its method of grouping statements. When a while loop is executed, expression is first evaluated in a Boolean context, and if it is true, the loop body is executed. Then the expression is rechecked. If it is still valid, the body is executed again, continuing until the expression becomes false.

            Let’s have a look at the flow chart of ‘while loop’

python program to calculate power without using pow method

Our Logic to calculate the power

  • Our program will take two inputs a base number and an exponent number from the user.
  • We will use ‘while loop’ with a condition that exponent number is not equal to 0, if become 0 while execution then our program execution needs to be out from the ‘while loop’ block.
  • Inside ‘while loop’ we will multiply exponent with base each time the ‘while loop’ executes and simultaneously we will decrement the value of exponent by 1.
  • Once our program came out from the ‘while loop’, we will print the value as an output of our program.

Python Code to calculate the power

base = int(input("Enter the value for base: "))
exponent = int(input("Enter the value for exponent: "))
result=1;
print(base," to power ",exponent,"=",end = ' ')
#using while loop with a condition that come out of while loop if exponent is 0
while exponent != 0:
    result = base * result
    exponent-=1
print(result)

Output:

Enter the value for base: 5
Enter the value for exponent: 4
5  to power  4 = 625

Explanation:

For the input from the user, the base number is 5, and the exponent number is 4. The ‘base e exponent’ will be 54, which is 5x5x5x5 i.e. 625.

What did you think?

Similar Reads

Hi, Welcome back!
Forgot Password?
Don't have an account?  Register Now