3 ways to square a number in Python


Today’s practice question requires us to write a Python function to find the square of a number.

Here are some topics we’ll cover in the post:

Key Concepts

Let’s cover some background information before we get started.

There are three ways to square a number in Python:

  • multiplying a number by itself
  • using the ** operator
  • using the built-in pow() function

Multiplying a number by itself

The easiest way to square a number in Python is to multiply the number by itself.

For instance, to get the square of 7, we simply take 7*7. We’ll get 49 as the output.

Other examples include:

4*4 = 16
8*8 = 64

Using the ** operator

Another way is to use the ** operator (also known as the exponent or power operator). This operator raises the first operand to the power of the second.

For instance, when we write 2**3, the operator raises 2 to the power of 3. In other words, we get 23 = 2x2x2 = 8.

Other examples include:

4**2 = 16
(-5)**4 = 625
2.1**2 = 4.41

Using the built-in pow() function

The final way is to use a built-in function called pow(). This function takes two values, raises the first value to the power of the second, and returns the result.

For instance, pow(2, 5) raises 2 to the power of 5. In other words, we get 25 = 32.

Other examples include:

pow(3, 4) = 81
pow(-2, 4) = 16

Practice Question

Today’s practice question requires us to write a simple Python function called square() that accepts a numerical input and returns the square of the input.

You need to check if the input is valid. If it is not, the function returns -1. Else, it returns the result.

Expected Results

To test your function, you can run the following statements:

print(square('ABDC'))
print(square(5))
print(square(-2))
print(square(3.1))

You should get the following results:

-1
25
4
9.61

Additional Notes

Floating Point Numbers

Regardless of which method we use to get the square of a number, an issue may arise when you try to square a floating-point number (i.e. a number with a decimal component, such as 1.6, 2.51 etc).

For instance, if you do a 1.6*1.6, you may get 2.5600000000000005 (instead of 2.56) as the result.

This is not due to a bug in our code or in Python.

Rather, it is due to the way floating-point numbers (i.e. numbers with decimal parts) are represented in our computers. A discussion of floating-point numbers is beyond the scope of this post. If you are interested, you can check out the following website: https://docs.python.org/3/tutorial/floatingpoint.html

If you do not want the output to be 2.5600000000000005, you may want to use another built-in function round() to round the result to a specific decimal place.

For instance, round(1.23456, 4) rounds the number 1.23456 to 4 decimals places. You’ll get 1.2346 as the result.

round(pow(1.6, 2), 4) rounds the result of pow(1.6, 2) to 4 decimal places. You’ll get 2.56 as the result.

To determine if an input is valid

Another part of today’s practice question requires us to return -1 when the input to the square() function cannot be squared. This happens when the input is not numerical.

The easiest way to do this is to use a try-except statement. The syntax is as follows:

try:
    # do task A
except:
    # do this if task A fails

Let’s look at an example:

try:
    print(pow('abc', 2))
except:
    print('-1')

Here, we first try to print the output of pow('abc', 2). As a string cannot be raised to the power of 2, the try block (i.e. line 2) fails. When that happens, the code in the except block (i.e. line 4) is executed.

If you run the code above, you’ll get -1 as the output.

Suggested Solutions

Here are some suggested solutions to today’s practice question.

Click to see the solutions

Solution 1

def square(a):
    try:
        return round(a*a, 6)
    except:
        return -1

This function accepts an input a and tries to execute the code in the try block. In other words, it tries to execute line 3.

Line 3 does the following:

It first multiples a by itself. Next, it passes the result of a*a to the round() function to round the result to 6 decimal places. Finally, it uses the return keyword to return the result.

If line 3 fails, the except block (i.e. line 5) will be executed. This line returns the value -1.

Solution 2

def square(a):
    try:
        return round(a**2, 6)
    except:
        return -1

This function is similar to the function in solution 1. The only difference is it uses the ** operator to raise a to the power of 2.

Solution 3

def square(a):
    try:
        return round(pow(a, 2), 6)
    except:
        return -1

This function is similar to the previous 2. The difference is that it uses the pow() function to raise a to the power of 2.

Written by Jamie | Last Updated September 1, 2020

Recent Posts