Squared number in python

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.

Читайте также:  Untitled Document

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

Источник

How to Square a Number in Python – Squaring Function

Dillion Megida

Dillion Megida

How to Square a Number in Python – Squaring Function

To square a number, you multiply that number by itself. And there are multiple ways to do this in Python.

You can directly multiple a number by itself (number * number) but in this article, I’ll show you three ways you can do this without hardcoding both numbers.

  • **, the power operator
  • the in-built pow() function
  • the math.pow() function from the math module

How to Use the Power Operator (**) in Python

** is called the power operator. You use it to raise a number to a specified power. Here is the syntax:

The expression above is evaluated as number * number. (for as many times as the value of the exponent). You can also read the expression as 5 2 .

Using this operator, you can find the square of a number using 2 as the exponent. For example, to find the square of 5, you can do this:

square = 5 ** 2 print(square) # 25 

The power operator evaluates the expression as 5 * 5, which results in 25.

How to Use the pow() Function in Python

Python has an inbuilt pow() function, which evaluates a number to the power of another number. Here’s the syntax:

pow(base, exponent) // interpreted as ^3 

The code above is interpreted as base exponent .

The function accepts two arguments: the number to be raised (known as the base) and the power the number should be raised to (the exponent).

To find the square of a number using this function, the number will be the base, and the exponent will be 2, which means number 2 .

To find the square of 5, for example, you can use this function like this:

square = pow(5, 2) print(square) # 25 

The pow() function also receives a third argument: the modulo. The sign for modulo is %. This argument evaluates the remainder when a value is divided by another.

For example, 5 % 2 gives 1 because 5 divided by 2 is 2, remainder 1.

Applying the modulo the pow() function looks like this:

mod = pow(5, 2, 3) print(mod) ## 1 ## 5 * 5 is 25 ## 25 % 3 is 1 

According to the python documentation on pow, this approach computes more efficiently than pow(5,2) % 3

How to USe the math.pow() Function in Python

math.pow() comes from Python’s math module. This function is similar to the in-built pow() function in usage and syntax, except that it has two differences:

  • it only accepts two arguments: the base and the exponent
  • it always returns a float number even when the raised number is a whole number.

So, math.pow(5, 2) returns 25.0.

pow() will only return a float number when the number is a float. It will return an integer if the number is whole. But math.pow() always returns a float number.

Now you know how to square numbers in Python! Thank you for reading.

Dillion Megida

Dillion Megida

Developer Advocate and Content Creator passionate about sharing my knowledge on Tech. I simplify JavaScript / ReactJS / NodeJS / Frameworks / TypeScript / et al My YT channel: youtube.com/c/deeecode

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

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