How to write square root in Python?
Python has a predefined sqrt() function that returns the square root of a number. It defines the square root of a value that multiplies itself to give a number. The sqrt() function is not used directly to find the square root of a given number, so we need to use a math module to call the sqrt() function in Python.
For example, the square root of 144 is 12.
Using math.sqrt() method
The sqrt() function is an inbuilt function that returns the square root of any number. Following are the steps to find the square root of a number.
- Start the program
- Define any number whose square root to be found.
- Invoke the sqrt() function and pass the value that you have defined in step 2 and store the result in a variable.
- Print the square root.
- Terminate the program.
Let’s create a Python program to find the square root of a number.
SqrRoot.py
Output:
Let’s create a python program that finds the square root of a decimal numbers.
SqrRoot.py
Output:
In the following program, we have read a number form the user and find the square root.
SqRoot_Usr.py
Output:
Using math.pow() function
The pow() is an inbuilt function that is used in Python to return the power of a number. It has two parameters. The first parameter defines the number and second parameter defines the power raise to that number.
Pow_Sqrt.py
Output:
Using ** Operator
We can also use the exponent operator to find the square root of the number. The operator can be applied between two operands. For example, x**y. It means that left operand raised to the power of right.
Following are the steps to find the square root of a number.
Step 1. Define a function and pass the value as an argument.
Step 2. If the defined number is less than 0 or negative, it returns nothing.
Step 3. Use the exponential ** sign to find the power of a number.
Step 4. Take the numeric value from the user.
Step 5. Call the function and store its output to a variable.
Step 6. Display the Square Root of a number in Python.
Step 7. Exit from the program.
Let’s implement the above steps in a Python program and calculate the square root of a number.
SqrtFun.py
Output:
As we can see in the above example, first we take an input (number) from the user and then use the exponent ** operator to find out the power of a number. Where 0.5 is equal to √ (root symbol) to raise the power of a given number.
Let’s create a Python program that finds the square root of between the specified range. In the following program, we have found the square root of all the number between 0 to 50.
Sqrloop.py
Output: