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

avatar

Borislav Hadzhiev

Wed Apr 20 20221 min read

banner

Photo by Aaron Lee

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

The Python "NameError: name 'randint' is not defined" occurs when we use the randint function without importing it first. To solve the error, import the randint function before using it - from random import randint.

nameerror name randint is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ NameError: name 'randint' is not defined n1 = randint(1, 10) print(n1)

To solve the error, we have to import the randint function from the random module.

main.py
# ✅ import randint function first from random import randint n1 = randint(1, 10) print(n1)

Even though the random module is in the Python standard library, we still have to import it before using it.

Make sure you haven't misspelled randint in the import statement as function names are case-sensitive.

Also, make sure you haven't imported randint in a nested scope, e.g. a function. Import the function at the top level to be able to use it throughout your code.

The random.randint function takes 2 numbers - a and b as parameters and returns a random integer in the range.

Note that the range is inclusive - meaning both a and b can be returned.

The random module is most commonly used to generate a random number from a range or select a random element from a sequence.

You can view all of the functions the random module provides by visiting the official docs.

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