NameError is an error that is raised by the python when it is unable to find or recognize the variable in the code. Nameerror: name random is not defined as one of them. In this tutorial, you will know how to solve this Nameerror: name random is not defined Error.
Causes of Nameerror: name random is not defined Error
This NameError occurs due to the following reasons.
Cause 1: Forgetting to import a module
If you are trying to use the functions or variables from a module, but you have not imported it, you will get a
You will get the error when you run the below lines of code.
# Generate a random integer between 1 and 10 random_num = random.randint(1, 10) print(random_num)
NameError: name 'random' is not defined
Cause 2: A misspelling or incorrect casing
Python is case-sensitive, so if you misspell the name or use incorrect casing for a variable or function, you will get a
NameError. Check your code to ensure that you are using the correct spelling and casing.
Cause 3: Scope issues
If you are trying to access a variable outside of its defined scope, you will encounter a
NameError. Make sure that the variable you are referencing is in the correct scope and has been defined before usage.
The solution of the name random is not defined
To easily solve this error you have to first import the random module before using the random function. In most cases, the coder gets the due to it.
Now you will not get the error when you will run the below lines of code.
import random # Generate a random integer between 1 and 10 random_num = random.randint(1, 10) print(random_num)
Another solution is to use the correct spelling of the random module.
The Nameerror: name random is not defined error encounters when you are using the random module functions without importing the random module. The above is the solution to the error you are getting while coding.