What is a Square of Number?
Before heading to code, let’s start with the basics to get everyone on the same page.
6² – Here 6 is the base and 2 is the exponent. So, it equals to 6 times 6 (6 * 6). We can also read it like 6 raised to 2.
But more generally, we generally refer it as Square.
How to calculate the square of any number?
We just need to multiply the value with itself.
e.g.
5² = 5 * 5 = 25
6² = 6 * 6 = 36
Note
-> No matter, if the value is positive or negative, the square of any number is always positive.
Python 3 – Function to get Square of a number
# Take the number as input
number = int(input('Enter a number to get its square '))
# Define a function to calculate Square
def calculateSquare(num):
return num*num
# print the output
print("Square of ",number, "is ", calculateSquare(number))
Output

Explanation of the Code
number = int(input('Enter a number to get its square '))
First Of all, we are taking input from the user. And then typecasting it into an Integer. Because by default, input() function returns the String.
def calculateSquare(num):
return num*num
This is the function that takes the Integer and returns the Square of that Integer.
print("Square of ",number, "is ", calculateSquare(number))
Finally, we are passing the number calculateSquare(number)
and simultaneously printing the output as well.
Get Square of a number using Exponent Operator in Python
**
is the exponential operator in Python.
# Take the number as input
number = int(input('Enter a number to get its square '))
# print the output
print("Square of ",number, "is ", number ** 2)
Also Read – Calculate Square root in C++
Calculate Square of any Number using pow() function in Math Module
import math
number = int(input('Enter a number to get its square '))
# print the output
print("Square of ",number, "is ", math.pow(number, 2))
Explanation
pow()
function takes two parameters. First one is the Base Value and second one is the exponential value. As we need to calculate square, our exponential value is fixed to 2.
To use this function, we need to import math
module in our code.
Wrapping Up
I hope, now you can easily calculate the square of any number in Python 3. If you have any doubts regarding the code or if you are having a better solution the do share with us in the comments below.
Leave a Reply