Squared numbers in python

How to square numbers in Python?

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.

Table of Contents- Python Square

Squaring numbers in Python:

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:

The last method can also be used with the math module which has a lot of other handy mathematical functions as well.

Python Square using **:

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.

Code and Explanation:

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.

Squaring using the pow() method:

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.

Code and Explanation:

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.

Читайте также:  Heroku python supported versions

Multiplying the number by itself:

This is the most fundamental method of calculating the square of a number. Here we square the number by multiplying the number by itself.

Code and Explanation:

n = 2 n2 = 3 print(n*n) print(n2*n2) 

The above code returns the square of the number.

Closing thoughts — Python Square

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.

Источник

Squaring in Python: 4 Ways How to Square a Number in Python

Squaring in Python: 4 Ways How to Square a Number in Python

If you want to square a number in Python, well, you have options. There are numerous ways and approaches to Python squaring, and today we’ll explore the four most common. You’ll also learn how to square Python lists in three distinct ways, but more on that later.

Let’s get started with the first Python squaring approach — by using the exponent operator (**).

  • Square a Python Number Using the Exponent Operator (**)
  • Python’s Math Library — Square Numbers With the pow() Function
  • Square a Python Number with Simple Multiplication
  • Numpy — How to Square a Number with Numpy’s square() Function
  • Bonus: 3 Ways to Square a Python List
  • Summing up Python Squaring

Square a Python Number Using the Exponent Operator (**)

The asterisk operator in Python — ** — allows you to raise a number to any exponent. It’s also used to unpack dictionaries, but that’s a topic for another time.

On the left side of the operator, you have the number you want to raise to an exponent, and on the right side, you have the exponent itself. For example, if you want to square the number 10, you would write 10**2 — it’s that easy.

Let’s take a look at a couple of examples:

a = 5 b = 15 c = 8.65 d = -10  # Method #1 - The exponent operator (**) a_squared = a**2 b_squared = b**2 c_squared = c**2 d_squared = d**2  # Print print("Method #1 - The exponent operator (**)") print("--------------------------------------------------") print(f"a> squared = a_squared>") print(f"b> squared = b_squared>") print(f"c> squared = c_squared>") print(f"d> squared = d_squared>") 

Below you’ll see the output of the code cell:

Image 1 - Squaring method 1 (image by author)

And that’s how you can square, or raise a number to the second power by using the asterisk operator.

But what if you want to change the exponent? Simply change the number on the right side of the operator:

print("Method #1 - The exponent operator (**) (2)") print("--------------------------------------------------") print(f"a> to the power of 3 = a**3>") print(f"d> to the power of 5 = d**5>") 

Image 2 - Squaring method 1 (2) (image by author)

Python’s Math Library — Square Numbers With the pow() Function

The math module is built into Python and packs excellent support for mathematical functions. One of these functions is pow() , and it accepts two arguments:

Let’s modify the code snippet from earlier to leverage the math module instead:

import math  a = 5 b = 15 c = 8.65 d = -10  # Method #2 - math.pow() function a_squared = math.pow(a, 2) b_squared = math.pow(b, 2) c_squared = math.pow(c, 2) d_squared = math.pow(d, 2)  # Print print("Method #2 - math.pow() function") print("--------------------------------------------------") print(f"a> squared = a_squared>") print(f"b> squared = b_squared>") print(f"c> squared = c_squared>") print(f"d> squared = d_squared>") 

Image 3 - Squaring method 2 (image by author)

The output is nearly identical to what we had before, but the math module converts everything to a floating point number, even if there’s no need for it. Keep that in mind, as it’s an additional casting step if you explicitly want integers.

As you would imagine, raising a number to any other exponent is as easy as changing the second argument value:

print("Method #2 - math.pow() function (2)") print("--------------------------------------------------") print(f"a> to the power of 3 = math.pow(a, 3)>") print(f"d> to the power of 5 = math.pow(d, 5)>") 

Image 4 - Squaring method 2 (2) (image by author)

Let’s take a look at another, more manual approach to Python squaring.

Square a Python Number with Simple Multiplication

There’s no one stopping you from implementing squaring in Python by multiplying the number with itself. However, this approach isn’t scalable. It’s fine if you want to simply square a number, but what if you want to raise the number to a power of ten?

Here’s an example of how to square a number by multiplying it by itself:

a = 5 b = 15 c = 8.65 d = -10  # Method #3 - Multiplication a_squared = a * a b_squared = b * b c_squared = c * c d_squared = d * d  # Print print("Method #3 - Multiplication") print("--------------------------------------------------") print(f"a> squared = a_squared>") print(f"b> squared = b_squared>") print(f"c> squared = c_squared>") print(f"d> squared = d_squared>") 

The results are identical to what we had in the first example:

Image 5 - Squaring method 3 (image by author)

If you want to raise a number to some other exponent, this approach quickly falls short. You need to repeat the multiplication operation many times, which isn’t convenient:

print("Method #3 - Multiplication (2)") print("--------------------------------------------------") print(f"a> to the power of 3 = a * a * a>") print(f"d> to the power of 5 = d * d * d * d * d>") 

Image 6 - Squaring method 3 (2) (image by author)

The results are still correct, but they’re prone to errors that wouldn’t happen if you were using any other approach.

Numpy — How to Square a Number with Numpy’s square() Function

Python’s Numpy library is a holy grail for data scientists. It allows for effortless work with N-dimensional arrays, but it can also handle scalars.

Numpy’s square() function will raise any number or an array to the power of two. Let’s see how to apply it to our previous code snippet:

import numpy as np  a = 5 b = 15 c = 8.65 d = -10  # Method #4 - Numpy a_squared = np.square(a) b_squared = np.square(b) c_squared = np.square(c) d_squared = np.square(d)  # Print print("Method #4 - Numpy") print("--------------------------------------------------") print(f"a> squared = a_squared>") print(f"b> squared = b_squared>") print(f"c> squared = c_squared>") print(f"d> squared = d_squared>") 

The results are displayed below:

Image 7 - Squaring method 4 (image by author)

The one limitation of the square() function is that it only raises a number/array to the power of two. If you need a different exponent, use the power() function instead:

print("Method #4 - Numpy (2)") print("--------------------------------------------------") print(f"a> to the power of 3 = np.power(a, 3)>") print(f"d> to the power of 5 = np.power(d, 5)>") 

Image 8 - Squaring method 5 (image by author)

And that does it for squaring Python numbers. Let’s see how to do the same to Python lists next.

Bonus: 3 Ways to Square a Python List

As a data scientist, you’ll spend a lot of time working with N-dimensional arrays. Knowing how to apply different operations to them, such as squaring each array item is both practical and time-saving. This section will show you three ways to square a Python list.

Method 1 — Looping

The first, and the most inefficient one is looping. We have two Python lists, the first one stores the numbers, and the second will store the squared numbers. We then iterate over the first list, square each number, and append it to the second one.

arr = [5, 15, 8.65, -10] squared = []  # Method 1 - Looping for num in arr:  squared.append(num**2)  # Print print("Method #1 - Looping") print("--------------------------------------------------") print(squared) 

Image 9 - Squaring a Python list with looping (image by author)

Iterating over an array one item at a time isn’t efficient. There are more convenient and practical approaches, such as list comprehension.

Method 2 — List comprehension

With list comprehensions, you declare a second list as a result of some operation applied element-wise on the first one. Here we want to square each item, but the possibilities are endless.

Take a look at the following code snippet:

arr = [5, 15, 8.65, -10]  # Method 2 - List comprehensions squared = [num**2 for num in arr]  # Print print("Method #2 - List comprehensions") print("--------------------------------------------------") print(squared) 

The results are identical, but now take one line of code less:

Image 10 - Squaring a Python list with list comprehensions (image by author)

Let’s switch gears and discuss you can square an array in Numpy.

Method 3 — Numpy

Remember the square() function from the previous section? You can also use it to square individual array items. Numpy automatically infers if a single number or an array has been passed as an argument:

arr = np.array([5, 15, 8.65, -10])  # Method 3 - Numpy squared = np.square(arr)  # Print print("Method #3 - Numpy") print("--------------------------------------------------") print(squared) 

Image 11 - Squaring a Python list with Numpy (image by author)

The Numpy array elements now have specific types — numpy.float64 — so that’s why you see somewhat different formatting when the array is printed.

And that’s how easy it is to square a number or a list of numbers in Python. Let’s make a short recap next.

Summing up Python Squaring

It’s almost impossible to take a beginner’s programming challenge without being asked to write a program that squares an integer and prints the result.

Now you know multiple approaches to squaring any type of number, and even arrays in Python. You’ve also learned how to raise a number to any exponent, and why some approaches work better than others.

Stay tuned to the blog if you want to learn the opposite operation — square roots — and what options you have in Python programming language.

Stay connected

Dario Radečić

Dario Radečić

Data Scientist & Tech Writer | Senior Data Scientist at Neos, Croatia | Owner at betterdatascience.com

Источник

Оцените статью