Python - Find the Power of a Number

In this program, you will learn how to find the power of a number.


Program 1: Calculate power of a number using a while loop



    base = int(input('Enter the base value: '))
    exponent = int(input('Enter the exponent value: '))
    
    result = 1
    
    while exponent != 0:
        result *= base
        exponent -= 1
    print("Result = " + str(result))

Output



    Enter the base value: 2
    Enter the exponent value: 5
    Result = 32

In this program, the base and exponent are holding the values for given numbers.
We keep on multiplying the result by base until the exponent becomes zero using while loop.
For example, it multiply result by base in 5 times toal, so result = 1 * 2 * 2 * 2 * 2 * 2 = 32

Program 2: Calculate power of a number using a for loop



    base = int(input('Enter the base value: '))
    exponent = int(input('Enter the exponent value: '))
    
    result = 1
    for exponent in range(exponent, 0, -1):
        result *= base
    
    print("Result " + str(result))

Output



    Enter the base value: 3
    Enter the exponent value: 4
    Result 81

In this program, we are using for loop instead of while loop. After each iteration, the exponent is decremented by 1, and the result is multiplied by the base exponent numer of times.
For example, it multiply result by base in 4 times toal, so result = 1 * 3 * 3 * 3 * 3 = 81

Program 3: Calculate power of a number using pow() function



The above two programs do not work with negative numbers. So, you need to use pow() function in Python library.


    base = int(input('Enter the base value: '))
    exponent = int(input('Enter the exponent value: '))
    
    result =  pow(base, exponent)
    
    print("Result " + str(result))
    
    

Output



    Enter the base value: 2 
    Enter the exponent value: -4
    Result 0.0625

In this program, we are using for pow() function which accepts two arguments base and exponenet.
For example, 2 raised to the power -4 which returns 0.0625 using pow().



The following topics can be useful to understand this program.



Related Tutorials