Finding a square root is a common task in mathematics and coding, and Python provides a simple way to accomplish this task. In this tutorial, we will cover how to get the square root in Python.
Step 1: Import the math library
The first step is to import the math library in Python. This library contains various mathematical functions, including a function to find the square root.
1 |
import math |
Step 2: Use the math.sqrt() function
After importing the math library, you can use the math.sqrt() function to find the square root of a number. You just need to pass the number as an argument to the function.
1 2 |
sqrt_val = math.sqrt(16) print(sqrt_val) |
The above code will output:
1 |
4.0 |
Step 3: Custom square root function (optional)
If you want to create your own function for finding square root, you can do that too. However, it’s always recommended to use built-in functions as they are more optimized.
1 2 3 4 |
def sqrt_custom(number): return number ** 0.5 sqrt_val_custom = sqrt_custom(16) print(sqrt_val_custom) |
The above code will output:
1 |
4.0 |
Full Code
Here’s the full code that incorporates everything we’ve discussed:
1 2 3 4 5 6 7 8 |
import math print(math.sqrt(16)) def sqrt_custom(number): return number ** 0.5 print(sqrt_custom(16)) |
The output will be:
1 2 |
4.0 4.0 |
Conclusion
In Python, finding the square root of a number is quite simple and straightforward because of the math.sqrt() function provided by the math library. This tutorial shows you how to use this function and also how to create your own custom function for finding the square root if you want to understand the underlying calculations.