
π Day 16/150 – Find Square of a Number in Python
Finding the square of a number is one of the most basic yet important operations in programming. It helps build a strong foundation for mathematical computations, algorithms, and problem-solving.
In this blog, we’ll explore multiple ways to calculate the square of a number in Python, along with simple explanations so you truly understand what’s happening behind the scenes.
Method 1 – Using Multiplication Operator
This is the most straightforward way.
✅ Explanation:
- num * num simply multiplies the number by itself.
- If num = 5, then 5 * 5 = 25.
π Best for beginners because it’s clear and easy to understand.
Method 2 – Using Exponent Operator **
Python provides a special operator for powers.
num = 5 square = num ** 2 print("Square:", square)
✅ Explanation:
- ** means “power of”
- num ** 2 means num raised to the power of 2
π Cleaner and more “Pythonic” than multiplication.
Method 3 – Taking User Input
Make your program interactive.
✅ Explanation:
- input() takes input as a string → converted to integer using int()
- Then we calculate the square
π Useful when building real applications.
Method 4 – Using a Function
Functions help in code reuse and better structure.
✅ Explanation:
- def defines a function
- return sends the result back
- You can reuse find_square() anywhere
π Best practice for clean and modular code.
Method 5 – Using Lambda Function
A short and quick way to write functions.
✅ Explanation:
- lambda creates an anonymous (one-line) function
- x * x computes the square
π Useful for small, quick operations.
✅ Explanation:
- lambda creates an anonymous (one-line) function
- x * x computes the square
π Useful for small, quick operations.
⚡ Key Takeaways
- ✔ Use num * num for clarity
- ✔ Use num ** 2 for cleaner syntax
- ✔ Use functions for reusable code
- ✔ Use lambda for quick one-liners
- ✔ Always validate input in real-world programs

0 Comments:
Post a Comment