Python program to calculate square of a given number
The task of calculating the square of a number in Python involves determining the result of multiplying a number by itself. For example, given the number 4, its square is 16 because 4 × 4 = 16.
Using ** operator
exponentiation operator (**) is the most direct and optimized way to compute powers. Since it is natively supported, it executes quickly with minimal overhead.
n = 4
res = n ** 2
print(res)
Output
16
Using math.pow()
math.pow() function provides a mathematical approach to computing squares. However, it returns a floating-point result, requiring conversion to an integer if needed.
import math
n = 4
res = math.pow(n, 2)
print(int(res)) # Convert to int if needed
Output
16
Using * operator
A simple and efficient way to square a number is by multiplying it by itself. This method is straightforward and efficient for most cases.
n = 4
res = n * n
print(res)
Output
16
Using loop
An alternative method to calculate the square is by repeatedly adding the number to itself n
times. While this works, it is not the best approach for squaring a number.
n = 4
res = sum(n for _ in range(n))
print(res)
Output
16