Borislav Hadzhiev
Wed Apr 20 2022·1 min read
Photo by Aaron Lee
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
.
Here is an example of how the error occurs.
# ⛔️ 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.
# ✅ 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.
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.