Python square number
Square of a number means number multiplied by itself. Example, 4 is the square of 2, 25 is the square of 5, 10000 is square of 100 etc.
In this article, we will understand how to find square of a number in python in different ways with example programs.
Python exponent operator is used to raise a number to the power of another number. Its symbol is
**and syntax is
a ** b
which results in ab or a raised to power of b.
Square of a number is 2 raised to the power of that number. This means that square of 5 is 52, square of 25 is 252 etc.
Thus, using exponent operator, we can find square of a number as follows
num = int(input('Enter a number: ')) square = num ** 2 print('Square of', num,' is',square)
Output of this program is
Enter a number: 35
Square of 35 is 1225
Method 2: Multiplication by self
Square of a number is the number multiplied by itself. Python program to find square of a number for this method is given below
num = int(input('Enter a number: ')) square = num * num print('Square of', num,'is',square)
Enter a number: 27
Square of 27 is 729
mathmodule has a
pow()function which takes two arguments. First is the number and seconds the power to which the number will be raised.
To find square of a number, we should supply number as the first argument and 2 as the second argument, since square of a number is, number raised to power 2. Example,
import math num = int(input('Enter a number:')) square = math.pow(num,2) print('Square of', num,'is',square)
pow() returns the result as a
float value. Output of above program is
Enter a number: 98
Square of 98 is 9604.0
Find square of list of numbers
Square of list means square of each element of a list. There are two ways to find square of a python list.
1. Iterate over the list using a loop. Find square of each element using any of the methods explained till now and add the result to a new list. Example,
l=[2,3,4,5] # define a list of squares squares= for x in l: squares.append(x**2) print(squares)
2. Use list comprehension
Python list comprehension also involves looping through the list but it has a more cleaner and concise syntax as shown below.
l=[2,3,4,5] # list comprehension squares=[ x**2 for x in l ] print(squares)
Output is the same.