Fix - NameError: name 'sqrt' is not defined in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Mike Rawlings

Fix - NameError: name 'sqrt' is not defined in Python #

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).

nameerror name sqrt is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ NameError: name 'sqrt' is not defined print(sqrt(25))

To solve the error, import the sqrt function from the math module.

main.py
# ✅ 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

main.py
from numpy import sqrt print(sqrt([1, 4, 9])) # 👉️ [1. 2. 3.]

Alternatively, you can import the entire module.

main.py
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.

main.py
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.

main.py
# ✅ import sqrt function first from math import sqrt print(sqrt(25)) # 👉️ 5.0
For example, when we use an import such as 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.