NameError: name 'random' is not defined in Python [Solved]

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
7 min

banner

# Table of Contents

  1. NameError: name 'random' is not defined in Python
  2. AttributeError module 'random' has no attribute 'randint'
  3. AttributeError module 'random' has no attribute 'choice'

# NameError: name 'random' is not defined in Python

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.

nameerror name random is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ NameError: name 'random' is not defined n1 = random.randint(1, 10) print(n1) s1 = random.choice(['a', 'b', 'c']) print(s1)

# Import the random module before using it

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

main.py
# ✅ Import the random module first import random n1 = random.randint(1, 10) print(n1) s1 = random.choice(['a', 'b', 'c']) print(s1)

import random module before using it

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 used a capital letter r when importing random because module names are case-sensitive.

# Make sure you haven't imported the module in a nested scope

Make sure you haven't imported random in a nested scope, e.g. a function.

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

importing the random module in nested scope

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.

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

move import statement to top of file

The import statement should be at the top of your file, before any lines that make use of the random module.

# Make sure to not import the random module in a try/except statement

You also should be importing the random module in a try/except statement.

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

importing random module in try except statement

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.

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

# Importing specific functions from the random module

An alternative to importing the entire random module is to import only the functions that your code uses.

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

For example, when we use an import such as 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.

# Conclusion

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.

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

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.

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

nameerror name randint is not defined

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

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

# AttributeError module 'random' has no attribute 'randint'

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.

attributeerror module random has no attribute randint

Here is an example of how the error occurs in a file called random.py.

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.

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

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

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

If you try to access any attribute that is not in this list, you will get the "AttributeError: module has no attribute".

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.

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

main.py
import sys # 👇️ print all built-in module names print(sys.builtin_module_names)

# AttributeError module 'random' has no attribute 'choice'

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.

attributeerror module random has no attribute choice

Here is an example of how the error occurs in a file called random.py.

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.

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

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

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

If you try to access any attribute that is not in this list, you will get the "AttributeError: module has no attribute".

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.

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

main.py
import sys # 👇️ print all built-in module names print(sys.builtin_module_names)
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.