Last modified: Mar 03, 2025 By Alexander Williams

Fix Python NameError: Name 'random' Not Defined

When working with Python, you might encounter the NameError: Name 'random' Not Defined error. This error occurs when you try to use the random module without importing it first.

What Causes the NameError?

The NameError is raised when Python cannot find a name in the current scope. In this case, it means that the random module is not imported before you try to use it.

For example, if you try to generate a random number without importing the random module, you will get this error:


    # This will raise a NameError
    print(random.randint(1, 10))
    

    NameError: name 'random' is not defined
    

How to Fix the NameError

To fix this error, you need to import the random module before using it. Here’s how you can do it:


    # Import the random module
    import random

    # Now you can use random functions
    print(random.randint(1, 10))
    

    7  # Example output
    

By importing the random module, Python recognizes the name and allows you to use its functions without any issues.

Common Mistakes to Avoid

Sometimes, even after importing the module, you might still encounter the NameError. This can happen if you misspell the module name or forget to import it in the correct scope.

For example, if you import the module inside a function, it won’t be available outside that function:


    def generate_random():
        import random
        return random.randint(1, 10)

    # This will raise a NameError
    print(random.randint(1, 10))
    

    NameError: name 'random' is not defined
    

To avoid this, always import modules at the top of your script or in the global scope.

Related Errors

If you encounter similar errors with other modules or names, such as NameError: Name 'math' Not Defined or NameError: Name 'os' Not Defined, the solution is the same. Always ensure that the module or name is imported or defined before use.

Conclusion

The NameError: Name 'random' Not Defined is a common issue in Python. It occurs when the random module is not imported before use. To fix it, simply import the module at the beginning of your script. Avoid common mistakes like misspelling or incorrect scope imports.

For more tips on handling Python errors, check out our guide on Handling NameError in Python Try-Except Blocks.