close

[Solved] NameError: global name ‘xrange’ is not defined in Python 3

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error NameError: global name ‘xrange’ is not defined in Python 3 in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How NameError: global name ‘xrange’ is not defined in Python 3 Error Occurs?

Today I get the following error NameError: global name ‘xrange’ is not defined in Python 3 in python.

How To Solve NameError: global name ‘xrange’ is not defined in Python 3 Error ?

  1. How To Solve NameError: global name 'xrange' is not defined in Python 3 Error ?

    To Solve NameError: global name 'xrange' is not defined in Python 3 Error or replace all uses of xrange(...) with range(...) in the codebase and then use a different shim to make the Python 3 syntax compatible with Python 2:

  2. NameError: global name 'xrange' is not defined in Python 3

    To Solve NameError: global name 'xrange' is not defined in Python 3 Error or replace all uses of xrange(...) with range(...) in the codebase and then use a different shim to make the Python 3 syntax compatible with Python 2:

Solution 1


You are trying to run a Python 2 codebase with Python 3. xrange() was renamed to range() in Python 3.

Run the game with Python 2 instead. Don’t try to port it unless you know what you are doing, most likely there will be more problems beyond xrange() vs. range().

For the record, what you are seeing is not a syntax error but a runtime exception instead.


If you do know what your are doing and are actively making a Python 2 codebase compatible with Python 3, you can bridge the code by adding the global name to your module as an alias for range. (Take into account that you may have to update any existing range() use in the Python 2 codebase with list(range(...)) to ensure you still get a list object in Python 3):

try:
    # Python 2
    xrange
except NameError:
    # Python 3, xrange is now named range
    xrange = range

# Python 2 code that uses xrange(...) unchanged, and any
# range(...) replaced with list(range(...))

or replace all uses of xrange(...) with range(...) in the codebase and then use a different shim to make the Python 3 syntax compatible with Python 2:

try:
    # Python 2 forward compatibility
    range = xrange
except NameError:
    pass

# Python 2 code transformed from range(...) -> list(range(...)) and
# xrange(...) -> range(...).

The latter is preferable for codebases that want to aim to be Python 3 compatible only in the long run, it is easier to then just use Python 3 syntax whenever possible.

Solution 2

add xrange=range in your code 🙂 It works to me.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read