Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Looping Statements

Calculate the power of a number using a loop - Python Program

Example 1 :

# Power using loop base = float(input("Enter base: ")) exp = int(input("Enter exponent: ")) result = 1 for _ in range(abs(exp)): result *= base if exp < 0: result = 1 / result print(f"{base} raised to the power {exp} = {result}")

Output

 
OUTPUT  :
Enter base: 2
Enter exponent: -3
2.0 raised to the power -3 = 0.125
 

Explanation

  • Loops abs(exp) times multiplying result by base.
  • Handles negative exponents by taking reciprocal.
  • Complexity: O(|exp|).

Example 2 : Advanced Program

def calculate_power_loop(base, exponent): """ Calculates the power of a number using a loop. Args: base (int or float): The base number. exponent (int): The non-negative exponent. Returns: int or float: The result of base raised to the power of exponent. """ if exponent < 0: print("Error: This program only handles non-negative exponents.") return None result = 1 for _ in range(exponent): result *= base return result # Get input from the user try: num_base = float(input("Enter the base number: ")) num_exponent = int(input("Enter the non-negative exponent: ")) power_result = calculate_power_loop(num_base, num_exponent) if power_result is not None: print(f"The result of {num_base} raised to the power of {num_exponent} is: {power_result}") except ValueError: print("Invalid input. Please enter valid numbers.")

Output

 
OUTPUT  :
Enter the base number: 2
Enter the non-negative exponent: 3
The result of 2.0 raised to the power of 3 is: 8.0
 

Explanation

calculate_power_loop(base, exponent) function:

  • This function takes two arguments: base(the number to be raised) and exponent (the power).
  • It includes an error check to ensure the exponentis non-negative, as the simple loop approach does not handle negative exponents.
  • resultis initialized to 1. This is important because any number raised to the power of 0 is 1, and it serves as the starting point for multiplication.
  • A forloop iterates exponent number of times. The _ is used as a placeholder variable because the loop counter itself is not needed within the loop body.
  • In each iteration, resultis multiplied by base, effectively performing base * base * ... for exponent
  • Finally, the calculated resultis returned.