NameError: global name #39;xrange#39; is not defined in Python 3(NameError:Python 3 中未定义全局名称“xrange)
问题描述
I am getting an error when running a python program:
Traceback (most recent call last):
File "C:Program Files (x86)Wing IDE 101 4.1srcdebug server\_sandbox.py", line 110, in <module>
File "C:Program Files (x86)Wing IDE 101 4.1srcdebug server\_sandbox.py", line 27, in __init__
File "C:Program Files (x86)Wing IDE 101 4.1srcdebug serverclassinventory.py", line 17, in __init__
builtins.NameError: global name 'xrange' is not defined
The game is from here.
What causes this error?
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.
这篇关于NameError:Python 3 中未定义全局名称“xrange"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:NameError:Python 3 中未定义全局名称“xrange"
基础教程推荐
- Python 的 List 是如何实现的? 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01