The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Light Drops

--

Chapters
00:00 Nameerror: Global Name 'Xrange' Is Not Defined In Python 3
00:26 Accepted Answer Score 736
01:42 Answer 2 Score 29
01:52 Answer 3 Score 5
02:01 Answer 4 Score 25
02:11 Thank you

--

Full question
https://stackoverflow.com/questions/1719...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x #range #runtimeexception #xrange

#avk47



ACCEPTED ANSWER

Score 736


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.




ANSWER 2

Score 29


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




ANSWER 3

Score 25


I solved the issue by adding this import
More info

from past.builtins import xrange



ANSWER 4

Score 5


Replace

Python 2 xrange to

Python 3 range

Rest all same.