In this short tutorial, we look at how we can use Python to square a number. We look at all the various methods and break them down for you.
This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts.
The square of a number is the result of multiplying the number by itself. In Python, we deal with a lot of square numbers – Data, Financial Analysis use them the most. Because of this high usage Python provides three methods to square a number: they are:
- Using the Exponent Operator
- Multiplying the number by itself (n*n)
- Using pow()
The last method can also be used with the math module which has a lot of other handy mathematical functions as well.
The Python exponent operator ** is used to perform an exponential calculation. It takes in 2 real numbers. The syntax is as follows.
Here “N” is the number and “power” is the number of times you would like to exponent the number. Since we are looking to square the number, we can pass 2 as the power. Similarly, If we were looking to cube the value we would pass 3.
n = 2 n2 = 3 print(n**2) print(n2**2)
The above code snippet returns the following values which are the square of the entered values. This is how you use exponents to calculate the square of a number.
The pow() method is another method in Python that can be used to square a number. This method also takes in two arguments in the following syntax.
This method is equivalent to the exponent methods and you can choose which method you would like to use. The pow() method supports a third argument which I would recommend reading about once you have practiced using it with two arguments.
n = 2 n2 = 3 print(pow(2,2)) print(pow(3,2))
Similar to the method above, the square values of the argument are returned. This is how you use the pow() method to calculate the square of a number.
As mentioned above the pow() method can also be used in the math module, however, it needs to be imported before it is used. Hence I would not recommend using it unless you are intending to use other methods from the module as well.
This is the most fundamental method of calculating the square of a number. Here we square the number by multiplying the number by itself.
n = 2 n2 = 3 print(n*n) print(n2*n2)
The above code returns the square of the number.
All the method methods above can be used to calculate the Python square of a number. Although 3 works well, I personally prefer using methods 1 or 2.
Once you are done with the tutorial I would recommend that you check out the Python square root method that is used to find the square root of a number.