Last updated: Apr 8, 2024
Reading time·7 min
The Python "NameError: name 'random' is not defined" occurs when we use the
random
module without importing it first.
To solve the error, import the random
module before using it -
import random
.
Here is an example of how the error occurs.
# ⛔️ NameError: name 'random' is not defined n1 = random.randint(1, 10) print(n1) s1 = random.choice(['a', 'b', 'c']) print(s1)
random
module before using itTo solve the error, we have to import the random module.
# ✅ Import the random module first import random n1 = random.randint(1, 10) print(n1) s1 = random.choice(['a', 'b', 'c']) print(s1)
Even though the random
module is in the Python standard library, we still have
to import it before using it.
r
when importing random
because module names are case-sensitive.Make sure you haven't imported random
in a nested scope, e.g. a function.
def get_int(): import random n1 = random.randint(1, 10) print(n1) # ⛔️ NameError: name 'random' is not defined print(random.randint(1, 10))
We imported the random
module in a function, so we aren't able to use it
outside of the function.
Import the module at the top level to be able to use it throughout your code.
# ✅ moved the import statement to the top of the file import random def get_int(): n1 = random.randint(1, 10) print(n1) print(random.randint(1, 10))
The import statement should be at the top of your file, before any lines that
make use of the random
module.
random
module in a try/except statementYou also should be importing the random
module in a
try/except statement.
try: # 👉️ Code here could raise an exception import random n1 = random.randint(1, 10) print(n1) except ImportError: print(random.randint(1, 10)) print(random.randint(1, 10))
The code sample works, however, if the code in the try
statement raises an
error, the random
module won't get imported successfully.
This would cause the error because we are trying to access properties on the
random
module in the outer scope and the except
block.
Instead, move the import statement to the top of the file.
import random try: # 👉️ Code here could raise an exception n1 = random.randint(1, 10) print(n1) except ImportError: print(random.randint(1, 10)) print(random.randint(1, 10))
random
moduleAn alternative to importing the entire random
module is to import only the
functions that your code uses.
# 👇️ Only import randint and choice functions from random import randint, choice n1 = randint(1, 10) print(n1) s1 = choice(['a', 'b', 'c']) print(s1)
The example shows how to import only the randint
and choice
functions from
the random
module.
Instead of accessing the members on the module, e.g. random.randint()
, we now
access them directly.
This should be your preferred approach because it makes your code easier to read.
import random
, it is much harder to see which functions from the random
module are being used in the file.Conversely, when we import specific functions, it is much easier to see which
functions from the random
module are being used.
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.
The Python "NameError: name 'random' is not defined" occurs when we use the
random
module without importing it first.
To solve the error, import the random
module before using it -
import random
.
If you get an error such as "NameError: name 'randint' is not defined", then you
have forgotten to import the randint
method from the random
module.
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 the `randint` function first from random import randint n1 = randint(1, 10) print(n1)
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.
The Python "AttributeError module 'random' has no attribute 'randint'" occurs
when we have a local file named random.py
and try to import from the random
module.
To solve the error, make sure to rename any local files named random.py
.
Here is an example of how the error occurs in a file called random.py
.
import random # ⛔️ AttributeError: module 'random' has no attribute 'randint' print(random.randint(1, 10))
The most likely cause of the error is having a local file named random.py
which shadows the random
module from the standard library.
Make sure to rename your local file to something other than random.py
to solve
the error.
import random print(random.randint(1, 10)) # 👉️ 4
You can access the __file__
property on the imported module to see whether it
is shadowed by a local file.
import random print(random.__file__) # ⛔️ The result is shadowed by a local file # /home/borislav/Desktop/bobbyhadz_python/random.py # ✅ The result is pulling in the correct module # /usr/lib/python3.10/random.py
A good way to start debugging is to print(dir(your_module))
and see what
attributes the imported module has.
Here is what printing the attributes of the random
module looks like when I
have a file random.py
in the same directory.
import random # ⛔️ ['__builtins__', '__cached__', '__doc__', '__file__', # '__loader__', '__name__', '__package__', '__spec__'] print(dir(random))
If you pass a module object to the dir() function, it returns a list of names of the module's attributes.
We can see that the imported random
module doesn't have a randint
attribute,
which makes it evident that we are shadowing the official random
module with
our local random.py
file.
If you try to import the random
module in a file called random.py
, you would
get a little different error message that means the same thing.
import random # ⛔️ AttributeError: partially initialized module 'random' has no attribute 'randint' (most likely due to a circular import) print(random.randint(1, 10))
Renaming your file solves the error.
You can use the sys
module to print all of the built-in module names if you
ever wonder if your local modules are clashing with built-in ones.
import sys # 👇️ print all built-in module names print(sys.builtin_module_names)
The Python "AttributeError module 'random' has no attribute 'choice'" occurs
when we have a local file named random.py
and try to import from the random
module.
To solve the error, make sure to rename any local files named random.py
.
Here is an example of how the error occurs in a file called random.py
.
import random # ⛔️ AttributeError: module 'random' has no attribute 'choice' print(random.choice(['a', 'b', 'c'])) print(random.choices(['a', 'b', 'c'], k=2))
The most likely cause of the error is having a local file named random.py
which shadows the random
module from the standard library.
Make sure to rename your local file to something other than random.py
to solve
the error.
import random print(random.choice(['a', 'b', 'c'])) # 👉️ b print(random.choices(['a', 'b', 'c'], k=2)) # 👉️ ['b', 'a']
You can access the __file__
property on the imported module to see whether it
is shadowed by a local file.
import random print(random.__file__) # ⛔️ The result is shadowed by a local file # /home/borislav/Desktop/bobbyhadz_python/random.py # ✅ The result is pulling in the correct module # /usr/lib/python3.10/random.py
A good way to start debugging is to print(dir(your_module))
and see what
attributes the imported module has.
Here is what printing the attributes of the random
module looks like when I
have a file random.py
in the same directory.
import random # ⛔️ ['__builtins__', '__cached__', '__doc__', '__file__', # '__loader__', '__name__', '__package__', '__spec__'] print(dir(random))
If you pass a module object to the dir() function, it returns a list of names of the module's attributes.
We can see that the imported random
module doesn't have a choice
attribute,
which makes it evident that we are shadowing the official random
module with
our local random.py
file.
If you try to import the random
module in a file called random.py
, you would
get a little different error message that means the same thing.
import random # ⛔️ AttributeError: partially initialized module 'random' has no attribute 'choice' (most likely due to a circular import) print(random.choice(['a', 'b', 'c'])) print(random.choices(['a', 'b', 'c'], k=2))
Renaming your file solves the error.
You can use the sys
module to print all of the built-in module names if you
ever wonder if your local modules are clashing with built-in ones.
import sys # 👇️ print all built-in module names print(sys.builtin_module_names)