Skip to main content
HomeTutorialsPython

How to Square a Number in Python: Basic Examples and Advanced Methods

Squaring in Python is easy: Use the in-built ** operator or try NumPy, pow(), math.pow(), bitwise operators, and other functions for more versatile solutions.
Jun 2024  · 11 min read

Python SquarePython Square. Image by Author using Dall-E.

Have you ever encountered an analysis problem requiring you to square a number in Python? It’s a common problem, and luckily Python has many ways to solve it. The Python square function is important in various tasks, such as financial analysis, when calculating risk returns. The method also helps in statistics and data analysis to calculate the variance and standard deviation of data.

In this tutorial, you will learn how to square a number for the different scenarios. You will also master the basic and advanced methods of how to square in Python. Our Introduction to Python course has a section explaining how to use Python for advanced calculations such as squaring.

The Quick Answer: How to Square a Number in Python

The simplest way to square a number in Python is by using the exponent operator **. For example, to square the number 6, we use the exponent as square6 = 6 ** 2. This exponent/power operator multiplies the number by itself to give the resulting square.

6 ** 2 # equals 36

In the interest of being thorough, I will explain the other methods I have used for Python square in the rest of this article, including pow() and math.pow() functions, list comprehension, NumPy library, while loop, and bitwise operators.

Squaring a Number Using the Exponent Operator

Python’s built-in exponent ** operator is the most common method for how to square in Python. This method raises the number to a power of 2 to square the number. 

# Define the number to be squared
number = 6
# Use the ** operator to square the number
squared_number = number ** 2
# Print the result
print(f"The square of {number} is {squared_number}")

Example output of Python square using exponent ** operator.

Example output of Python square using exponent ** operator. Image by Author.

The Python square method using the ** operator is simple. It is straightforward and does not need to import any libraries. The method is also efficient and can handle large datasets since it is implemented at a low level.

Understanding Squaring in Python and Why It’s Important

Squaring a number in Python is important for mathematical and statistical operations. As a data practitioner, you should understand when to apply Python square for different scenarios. Below are some examples of when to apply the method:

  1. Statistics: Squaring is used to calculate variance and standard deviation for advanced analysis in measures of dispersion. 
  2. Least Squares Method: Related to the concepts of variance and standard deviation, when fitting a model in linear regression, squaring the independent variable (x) optimizes the model’s performance by minimizing the sum of squares of the residuals.
  3. Loss Function in Machine Learning: Similar to the least squares method, the Python square calculates the model's performance by squaring the difference between the actual and predicted value.
  4. Finance: The Python square method calculates risk by squaring actual returns and the mean. It is also used for utility functions related to portfolio optimization.

If you need to refine your Python skills in statistics, DataCamp’s Data Analyst with Python course offers sufficient guidance on becoming a data analyst.

Different Techniques to Square Numbers in Python

There are various methods to square a number in Python, such as multiplication, the pow() function, math.pow() function, list comprehensions, the NumPy library, a while loop, and bitwise operations. Now, let us discuss how and when to apply each method.

First, you might be wondering: Do I need to learn so many different methods? Being familiar with multiple techniques to square numbers in Python offers several advantages:

  1. Versatility: Different methods are suitable for different situations. Some methods are more efficient for large-scale computations.
  2. Performance Optimization: Certain methods can be significantly faster or more efficient in terms of memory usage. Understanding these can help optimize your code, especially in performance-critical applications.
  3. Compatibility: Some methods are better suited for specific libraries or frameworks. For example, numpy is widely used in data science and machine learning for its optimized numerical operations.
  4. Code Readability and Maintainability: Different contexts might require different levels of code readability. Choosing the right method can make your code more understandable for others.
  5. Flexibility in Problem-Solving: Being versatile with different techniques allows you to tackle a wider range of problems and adapt to various coding scenarios more effectively.

Let’s take a look at different methods. 

Multiplication operator

The multiplication operator (*) is another method to square a number in Python. It is simple to use and does not require importing any modules. However, it is limited to basic use and may not be applied in advanced cases.

# Squaring a number using multiplication
number = 6
# Using multiplication operator
squared = number * number  
print(squared)

Example output of Python square using multiplication operator.

Example output of Python square using multiplication operator. Image by Author.

Using the pow() function

Python’s in-built pow() function also squares a number. This function takes two arguments: the number and the exponent of the number. Therefore, the second argument for a square function will always be 2 since you need to raise the number to a power of 2.

# Squaring a number using the pow() function
number = 6
# The first argument is the number, and the second argument is the exponent
squared = pow(number, 2)
print(squared)

Example output of Python square using pow() function.

Example output of Python square using pow() function. Image by Author.

The pow() function method is efficient for handling complex mathematical operations. It also supports the third argument (modulo operation) for some calculations.

# Squaring a number using the pow() function
number = 6
# Squaring a number with modulo using the pow() function
mod_squared = pow(number, 2, 7)
print(mod_squared)

For the above example, the output will be 1 since 36 % 7 is 1.

Example output of Python square using pow() function with modulo argument.

Example output of Python square using pow() function with modulo argument. Image by Author.

Using the math.pow() function

The math.pow() function is the Python math square function from the math module. Therefore, one needs to import the math module before calling the function. This function returns a float number, making it useful when handling float data types.

# Import the math module
import math
# Squaring a number using math.pow()
number = 5
squared = math.pow(number, 2)
print(squared)

Example output of Python square using math.pow() function.

Example output of Python square using math.pow() function. Image by Author.

Using list comprehension

List comprehension is useful when you want to square multiple numbers in a list. The method squares each element in the list to return another list with the squared numbers. Using list comprehension is useful for complex operations in lists by applying the same calculation to the list.

# Define the list
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10]
# Square each element in the list
squared_numbers = [x ** 2 for x in numbers]
print(squared_numbers)

Example output of Python square using list comprehension.

Example output of Python square using list comprehension. Image by Author.

Using NumPy library

The NumPy library has the square() function in Python. Thus, you must import the NumPy library before calling the function. This function is helpful when you want to square values in a large dataset. 

The square() function works by performing element-wise squaring of the datasets. The Python Cheat Sheet for Beginners also offers great insights on performing other statistical operations in Python.

# Import the numpy library with the alias np
import numpy as np
# Squaring a number using NumPy
number = np.array([5])
squared = np.square(number)
print(squared)

Example output of Python square using the NumPy library.

Example output of Python square using the NumPy library. Image by Author.

Using a while loop

The while loop is the least common method for finding the square of a number in Python. It is an iterative approach to squared numbers. The method is really only useful if you also added  more operations to the loop.

# Squaring numbers using a while loop
number = 5
squared = 0
i = 0
# Define the while loop function
while i < 1:
	squared = number * number
 i += 1
print(squared)

Example output of Python square using while loop.

Example output of Python square using while loop. Image by Author.

Using bitwise operators

Python square using bitwise operators is useful for particular calculations for low-level operations. This method squares the value in Python using bitwise left-shift operators.

# Squaring a number using bitwise left-shift operators.
number = 5
squared = (number << 2) + (number << 0)
# The above is equivalent to number * number but using bitwise operations
print(squared)

Example output of Python square using bitwise operators.

Example output of Python square using bitwise operators. Image by Author.

Comparison table

Below is a table where you can compare the different methods for squaring a number in Python. I suggest you note when each method is useful and easy to use.

Technique Use Case When It’s Useful Pros Cons
Multiplication operator Simple squaring Basic squaring operations Simple and no import of library needed Limited to only basic squaring
pow() function Complex mathematical operations, modulo When handling complex operations or needing modulo Handles complex mathematical operations and supports modulo More complex than the simple multiplication operator
math.pow() function Part of math module returns the float data type When using other math functions, dealing with float data types Useful when handling float data types Requires importing math module. Will always return float values
List comprehension Squaring elements in a list Applying operations to all elements in a list Useful when squaring numbers in a list Only limited to lists
NumPy library Squaring elements in large datasets Handling large datasets efficiently Efficient in large datasets Requires importing numpy library
While loop Iterative approach to squaring Specific scenarios requiring iteration Iterative approach, hence flexible Complex, hence less common
Bitwise operations Squaring using bitwise left-shift operations Low-level operations, specific use cases Efficient in low-level operations Limited to specific use cases and less readable

Best Practices and Guidelines

When squaring a number in Python, you may encounter some pitfalls based on your method. I have compiled some of the best practices to square a number according to the methods I have used during my practice.

Maintain immutability

When you want to square a value in Python, use variables to store the values to avoid modifying the original values. Similarly, create a new list for the squared number values rather than modifying the existing list.

# Store the number in a variable
number = 5
# Original 'number' remains unchanged
squared = number * number 
print(squared)

Example output of Python square while maintaining immutability.

Example output of Python square while maintaining immutability. Image by Author.

Optimize for performance

You should also optimize the code to perform optimally, especially when handling large datasets. Therefore, use the NumPy library when handling large datasets. Also, use list comprehensions over loops where necessary.

Handle edge cases

Ensure to handle edge cases for extreme or unexpected inputs. For example, the pow() function handles negative numbers and zeros, hence returns no errors.

Error handling and validation

Similarly, ensure errors or unexpected inputs are handled when squaring a value in Python. You can achieve that by using the try block in loops and functions.

# Importing the math module for mathematical functions
import math  
# Attempting to convert the input to float and square it
try:
    number = 'five' 
    squared = math.pow(float(number), 2)  
    print(squared)
except ValueError as e:
    # Catching and handling the ValueError that occurs when conversion to float fails
    print(f"Invalid input: {e}")

Example output of Python Square error handling and validations.

Example output of Python Square error handling and validations. Image by Author.

Conclusion

There are different methods on how to square a number in Python. These methods include using the multiplication operator, pow(), and math.pow() functions, list comprehensions, NumPy library, while loops, and bitwise operators. Each method has its specific use cases and advantages. As a Python user, you should know when to apply each method and best practices to achieve desired results.

If you are eager to sharpen your Python skills, I recommend taking DataCamp’s Python Fundamentals and Python Programming courses. The Python Developer course will also help you advance your Python skills as you prepare to take your career to the next level.


Photo of Allan Ouko
Author
Allan Ouko
I create articles that simplify data science and analytics, making them easy to understand and accessible.

Frequently Asked Questions

What is the simplest method to square a number in Python?

The simplest way to square a number is using the multiplication operator 5 * 5.

What is the difference between pow() and math.pow() functions?

The pow() function is an in-built Python function to square a number. It also supports a third argument, the modulo. However, the math.pow() function is imported from the math library and usually returns a float.

When is NumPy used to square a number?

You should use NumPy to perform square operations in large datasets.

How do I handle errors when squaring numbers in Python?

You can avoid errors by validating your code to handle exceptions where necessary.

Why should I avoid bitwise operations when squaring a number in Python?

Bitwise operations are less readable and should only be used for low-level operations.

Topics

Learn Python with DataCamp

course

Introduction to Python

4 hours
5.6M
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

cheat sheet

SciPy Cheat Sheet: Linear Algebra in Python

This Python cheat sheet is a handy reference with code samples for doing linear algebra with SciPy and interacting with NumPy.
Karlijn Willems's photo

Karlijn Willems

5 min

tutorial

Exponents in Python: A Comprehensive Guide for Beginners

Master exponents in Python using various methods, from built-in functions to powerful libraries like NumPy, and leverage them in real-world scenarios to gain a deeper understanding.
Satyam Tripathi's photo

Satyam Tripathi

9 min

tutorial

Usage of Asterisks in Python

Many Python users are familiar with using asterisks for multiplication and power operators, but in this tutorial, you'll find out additional ways on how to apply the asterisk.
Hafeezul Kareem Shaik's photo

Hafeezul Kareem Shaik

9 min

tutorial

Python Arrays

Python arrays with code examples. Learn how to create and print arrays using Python NumPy today!
DataCamp Team's photo

DataCamp Team

3 min

tutorial

Python Tutorial for Beginners

Get a step-by-step guide on how to install Python and use it for basic data science functions.
Matthew Przybyla's photo

Matthew Przybyla

12 min

tutorial

Python Absolute Value: A Quick Tutorial

Learn how to use Python's abs function to get a number's magnitude, ignoring its sign. This guide explains finding absolute values for both real and imaginary numbers, highlighting common errors.
Amberle McKee's photo

Amberle McKee

See MoreSee More