Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Operators and Expressions

Find the power of a number using ** and pow() - Python Program

To find the power of a number in Python, both the ** operator and the pow() function can be utilized.

Using the ** operator:

The ** operator is a binary operator used for exponentiation, where the left operand is the base and the right operand is the exponent.

 

base_num = 5 exponent_num = 3 result_operator = base_num ** exponent_num print(f"Using ** operator: {base_num} raised to the power of {exponent_num} is {result_operator}")

Output

 
OUTPUT  :
Using ** operator: 5 raised to the power of 3 is 125

Explanation: In this example, base_num ** exponent_num calculates 5 raised to the power of 3, which is

5×5×5=1255 cross 5 cross 5 equals 125

5×5×5=125

Using the pow() function: 

The pow() function is a built-in function that also calculates the power of a number. It takes two arguments: the base and the exponent. Optionally, a third argument can be provided for modular exponentiation.

 

base_num = 2 exponent_num = 4 result_function = pow(base_num, exponent_num) print(f"Using pow() function: {base_num} raised to the power of {exponent_num} is {result_function}") # Example with modular exponentiation base_num_mod = 3 exponent_num_mod = 2 modulus_num = 5 result_mod = pow(base_num_mod, exponent_num_mod, modulus_num) print(f"Using pow() for modular exponentiation: ({base_num_mod}^{exponent_num_mod}) % {modulus_num} is {result_mod}")

Output

 
OUTPUT  :
Using pow() function: 2 raised to the power of 4 is 16
Using pow() for modular exponentiation: (3^2) % 5 is 4

Explanation 

  • In the first pow() example, pow(base_num, exponent_num) calculates 2 raised to the power of 4, which is

2×2×2×2=162 cross 2 cross 2 cross 2 equals 16

2×2×2×2=16

 

  • In the second pow() example, pow(base_num_mod, exponent_num_mod, modulus_num) calculates

323 squared

32

(which is 9) and then finds the remainder when 9 is divided by 5, resulting in 4.