Nameerror: Name ‘random’ is not defined ( Solved )

Nameerror_ Name 'random' is not defined ( Solved )

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)

Output

Using randint() function without importing random module

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.

import random

Now you will not get the error when you run the below lines of code.

import random
r = random.randint(1,11)
print(r)

Output

solving the random namerror
solving the random namerror

Conclusion

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.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Sukesh ( Chief Editor ), a passionate and skilled Python programmer with a deep fascination for data science, NumPy, and Pandas. His journey in the world of coding began as a curious explorer and has evolved into a seasoned data enthusiast.
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner