How to Square Number in Python

Python is used extensively in the field of mathematics and statistics because of how easy it is to work with numbers.
One of the most common operations to do in any programming language is squaring a number.
In this post, we'll learn the three best ways to square a number in Python.
Multiplying a number by itself
The most straightforward way to square a number is to multiply it by itself.
That is because that is basically the definition of squaring a number.
Let's start off with the number we want to square:
number = 5
Now, we can square it by multiplying it by itself:
number = 5
number_squared = number * number
print(number_squared)
25
Using the exponent operator
Python has an exponent operator that can be used to square a number.
While the operator can support any exponent, we can use it to square a number by using the exponent of 2.
Let's start off with the number we want to square:
number = 5
Now, we can square it by using the exponent operator. To use the exponent operator, we simply put two asterisks (**) after the number we want to square:
number = 5
number_squared = number ** 2
print(number_squared)
25
Using the pow() function
The final way to square a number is to use the pow()
function.
This is a function that is built into Python and can be used to raise a number to any power.
To square a number, we simply pass in the number we want to square and the exponent of 2:
from math import pow
number = 5
number_squared = pow(number, 2)
print(number_squared)
25.0
Keep in mind that the output of the pow()
function is a float. If you want an integer, you can use the int()
function to convert it:
from math import pow
number = 5
number_squared = int(pow(number, 2))
print(number_squared)
25
Conclusion
In this post, we learned how to square a number in Python.
We learned how to do it by multiplying a number by itself, using the exponent operator, and using the pow()
function.
Thanks for reading and happy coding!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!