Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Mike Rawlings
The Python "NameError: name 'sqrt' is not defined" occurs when we use the
sqrt
function without importing it first. To solve the error import sqrt
from math
(from math import sqrt
). If using numpy
, import sqrt
from
numpy
(from numpy import sqrt
).
Here is an example of how the error occurs.
# ⛔️ NameError: name 'sqrt' is not defined print(sqrt(25))
To solve the error, import the sqrt function from the math module.
# ✅ import sqrt function first from math import sqrt print(sqrt(25)) # 👉️ 5.0
If you use numpy
, import the sqrt
function from the numpy
module instead
from numpy import sqrt print(sqrt([1, 4, 9])) # 👉️ [1. 2. 3.]
Alternatively, you can import the entire module.
import numpy as np print(np.sqrt([1, 4, 9])) # 👉️ [1. 2. 3.]
We imported the numpy
module and aliased it to np
, so we can access the
sqrt
function as np.sqrt()
.
You can use the same approach when using the build-in math
module.
import math print(math.sqrt(25)) # 👉️ 5.0
Even though the math
module is in the Python standard library, we still have
to import it before using it.
Make sure you haven't misspelled anything in the import statement because module and function names are case-sensitive.
Also, make sure you haven't imported the module in a nested scope, e.g. a function. Import the module at the top level to be able to use it throughout your code.
In general it is better to import only the functions you intend to use in your code.
# ✅ import sqrt function first from math import sqrt print(sqrt(25)) # 👉️ 5.0
import math
, it is much harder to see which functions from the math
module are being used in the file.Conversely, when we import specific functions, it is much easier to see which
functions from the math
module are being used.
The math
module provides access to many mathematical functions that are
defined by the C standard.
You can view all of the functions and constants the math
module provides by
visiting the official docs.