How to Square Number in Python

Updated onbyAlan Morel
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:

PYTHON
number = 5

Now, we can square it by multiplying it by itself:

PYTHON
number = 5 number_squared = number * number print(number_squared)
PYTHON
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:

PYTHON
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:

PYTHON
number = 5 number_squared = number ** 2 print(number_squared)
PYTHON
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:

PYTHON
from math import pow number = 5 number_squared = pow(number, 2) print(number_squared)
PYTHON
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:

PYTHON
from math import pow number = 5 number_squared = int(pow(number, 2)) print(number_squared)
PYTHON
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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.