You can do basic mathematical operations in Python easily. These can be done using operators such as +, -, *, / or %. There are many mathematical libraries such as math, NumPy, SciPy, Pandas, Matplotlib, and Sympy.
But if you want to perform some function such as determining the square root of a number there is a function called sqrt(), that is within the math module. sqrt() method can be used for finding the square root of a number.
In this article, we will focus on the different ways to determine the square root of a number.
1. Using math.sqrt() Method
In Python sqrt() function is an inbuilt function that returns the square root of any number given.
Syntax:
math.sqrt(x)
Parameter: Any number greater than 0 (Required)
Returns: square root of the number given
Code Example:
# Python program to calculate square root
import math
# Declare value to calculate square root
val = 12
if val > 0:
# Calculate square root using sqrt() method
sqr = math.sqrt(val)
print("Square Root of ", val,"is: ",sqr)
else:
print("Please give value greater then 0");
Output:
Square Root of 12 is: 3.4641016151377544
Explanation:
Here, the square root of the number is determined by the sqrt() method. But first, the value stored in variable val is checked to be positive or negative. This is because the square root of negative numbers cannot be determined. So, the if statement checks this condition by comparing whether the number stored in val is greater than 0, as positive numbers are always greater than 0.
If it is a positive number, then it is passed an argument to the sqrt() method. Hence, the square root of the number is determined.
2. Using "**" Operator
Exponents are used for raising a number to the given power. In Python, the ‘**’ operator is used to calculate the value of a number raised to a specified exponent.
Take a look at this example where the ** operator is used for finding the square root of a number.
Code Example:
# Declare value to calculate the square root
val = 12
# Calculate Square root
sroot = val**0.5
print("Square Root of ", val,"is: ",sroot)
Output:
Square Root of 12 is: 3.4641016151377544
Explanation:
You can observe that the ** operator is used for determining the exponential value of 2 raised to 0.5. This is actually giving the square root of 2. Thus with the help of ** operator, we can calculate the square root of any number.
Conclusion
Before using the different methods such as sqrt() remember to import the math module. It is best to use positive integers for these mathematical operations. This will reduce the complications in the code. When obtaining a value from the user, make sure to convert it to an integer using the int() method.