Nameerror: name random is not defined

In this article, we will hand you the solutions for Python’s “nameerror: name random is not defined” error message.

This error message is common in Python programming, and it is easy to fix with the right knowledge.

However, this error message is quite frustrating, especially if you don’t know how to fix it.

Fortunately, this article examines what this error means and why it occurs in your Python script.

What is random module?

The “random” module is a built-in Python library that you can use to generate pseudo-random numbers.

For instance, you can generate random integers within a specific range using the randint() function.

You can also generate random floating-point numbers using the random() function.

What is “nameerror: name random is not defined”?

The “nameerror: name ‘random’ is not defined” error message occurs when a Python interpreter encounters a variable or function named random that has not been defined.

In simple words, the error occurs when you are using the random module without importing it first.

Why does this error occur?

There are several reasons why you might encounter the “nameerror name random is not defined” error in Python. Here are the following:

❌ Forget to import the “random” module in your code.

❌ Importing the “random” module in the wrong namespace.

❌ Misspelling the “random” module in your code.

❌ Using a different name for the “random” module in your code

❌ Using an old version of Python that does not include the “random” module.

❌ Deleting or renaming the “random” module from your Python installation.

How to fix “nameerror: name random is not defined”?

To fix the “nameerror: name ‘random’ is not defined”, you just need to add the line import random at the top of your code.

This will allow you to use the functions and variables defined in the random module.

Import the “random” module

For example:

import random

# Now you can use functions from the random module
x = random.randint(10, 100)
print(x)

As you can see, this code imports the random module and then uses the randint() function from that module to generate a random integer between 10 and 100.

The print() function is used to display the result. Here the code runs smoothly as we first import the random module.

Output:

48

Conclusion

The “nameerror: name ‘random’ is not defined” error message occurs when a Python interpreter encounters a variable or function named random that it does not recognize or has not been defined.

This article already provides solutions that will help you to fix the error message.

You could also check out other “nameerror” articles that may help you in the future if you encounter them.

Hoping that this article helps you fix the error. Thank you for reading itsourcecoders 😊