In this tutorial, we will be discussing how to square a number in python. We will first discuss how to write the code, then give you some examples of how it can be used and finally discuss what is happening under the hood when you run your program.

How to Square A Number in Python code example

What Do You Need To Set Up?

We are going to start by importing the libraries that we need for this example: math and sys. After doing so, we are going to create an integer variable called “num” which will store the value of whatever number has been inputted into the program. Next, we want to compute the square of num using Python’s built-in function called “pow()”. Finally, our last step is printing out what was squared on-screen with a print statement.

This is what the finished product looks like:

import math
from sys import stdin

num = int(stdin.readline())
print("The square of {} is {}".format(num, math.pow(num, 2)))


The square of 2 is 4

What Does The Code Do To Square The Number?

When we run this code, it will first prompt us to input a number. Once we have done so, it will store that value in the “num” variable and then use Python’s built-in pow() function to calculate the square of that number. Finally, it prints out what was squared to the screen.

What Is Happening Underneath In The Libraries?

The code is using the pow() function built into the math library. This isn’t part of the core python code, so we had to import it. This function takes in two arguments- the number we want to square and the power to raise it to, in this case, 2 for squaring. It then calculates that value and returns it.