In most cases, the coder may encounter many exception errors in Python. NameError is one of them. In this post, you will know why the Nameerror: name ‘random’ is not defined error comes and how to solve it easily.
What is NameError?
NameError is a Python exception that occurs when you use the function or variable without defining it in the code. You will get the error also when you try to use the constructor without importing the Python module.
In the next section, you will know the main reason for getting the name random is not defined error.
Why Nameerror: name ‘random’ is not defined Error occurs?
The main or root cause for getting this error is that you must be using the random function or constructor without importing the module that contains random. You will get the error when you run below the lines of code.
r = random.randint(1,11) print(r)
You can see in the above code I want any random number generated between 1 and 11 but it gives the NameError.
Solve the name ‘random’ is not defined Error
The solution to this NameError is very simple. You have to first import the random module before using it in the code. You are getting the error as you are using the random.randint() function. So randint() function is for the random module. Thus you have to first import it. You can import it using the import statement.
Now you will not get the error when you run the below lines of code.
import random r = random.randint(1,11) print(r)
You are getting the name ‘random’ is not defined error as you don’t import the random module before using the random.randint() function. If you are getting this error then the above solution will solve it.
I hope you have liked this tutorial. If you have any queries then you can contact us for more help.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.