Home »
Python »
Python Programs
Python | Calculate square of a given number (3 different ways)
Square of a number in Python: In this tutorial, we will learn how to implement Python programs to calculate square of a given number using multiple approaches?
By IncludeHelp Last updated : April 13, 2023
The square of any number is considered as the number raised to the power of 2, in other words, the square of a given number N is the result of N*N or N2. Where N can be any integer number.
Problem statement
Given a number, and we have to calculate its square in Python.
Example
Consider the below example without sample input and output:
Input:
Enter an integer numbers: 8
Output:
Square of 8 is 64
Different Ways to Calculate Square of a Number in Python
The following are the different methods to calculate square of a given number in Python.
- By multiplying numbers two times: (number*number)
- By using Exponent Operator (**): (number**2)
- By using math.pow() method: (math.pow(number,2)
1) By multiplying numbers two times: (number*number)
To find the square of a number - simple multiple the number two times.
Example
# Python program to calculate square of a number
# Method 1 (using number*number)
# input a number
number = int (raw_input ("Enter an integer number: "))
# calculate square
square = number*number
# print
print "Square of {0} is {1} ".format (number, square)
The output of the above program is:
Enter an integer number: 8
Square of 8 is 64
2) By using Exponent Operator (**): (number**2)
The another way is to find the square of a given number is to use Exponent Operator (**), it returns the exponential power. This operator is represented by **
Example: Statement m**n will be calculated as "m to the power of n".
Example
# Python program to calculate square of a number
# Method 2 (using number**2)
# input a number
number = int (raw_input ("Enter an integer number: "))
# calculate square
square = number**2
# print
print "Square of {0} is {1} ".format (number, square)
The output of the above program is:
Enter an integer number: 8
Square of 8 is 64
3) By using math.pow() method: (math.pow(number,2)
pow(m,n) is an inbuilt method of math library, it returns the value of "m to the power n". To use this method, we need to import math library in the program.
The statement to import math library is import math.
Example
# Python program to calculate square of a number
# Method 3 (using math.pow () method)
# importing math library
import math
# input a number
number = int (raw_input ("Enter an integer number: "))
# calculate square
square = int(math.pow (number, 2))
# print
print "Square of {0} is {1} ".format (number, square)
The output of the above program is:
Enter an integer number: 8
Square of 8 is 64
Python Basic Programs »