π Day 43/150 – Power of a Number in Python
Finding the power of a number means raising a number to an exponent.
Example:
2³ = 2 × 2 × 2 = 8
5² = 25
Let’s explore different ways to calculate power in Python π
πΉ Method 1 – Using ** Operator
base = 2 exp = 3 result = base ** exp print("Power:", result)✅ Easiest and most common method.
πΉ Method 2 – Using pow() Function
base = 2 exp = 3 result = pow(base, exp) print("Power:", result)✅ Built-in function for power calculation.
πΉ Method 3 – Using Loop
base = 2 exp = 3 result = 1 for i in range(exp): result *= base print("Power:", result)
✅ Good for understanding logic.
πΉ Method 4 – Taking User Input
base = int(input("Enter base: ")) exp = int(input("Enter exponent: ")) print("Power:", base ** exp)
✅ Dynamic version.
πΉ Method 5 – Using Recursion
def power(base, exp): if exp == 0: return 1 return base * power(base, exp - 1) print(power(2, 3))
✅ Great for learning recursion.
πΉ Output
Power: 8
π₯ Key Takeaways
✔️ ** is the simplest way
✔️ pow() is built-in alternative
✔️ Loops help understand logic
✔️ Recursion builds concepts


0 Comments:
Post a Comment