'exit' 不是 Python 中的关键字,但使用时没有出现错误
'exit' is not a keyword in Python, but no error occurs while using it
我了解到 exit
不是 Python 中的关键字,
import keyword
print('exit' in keyword.kwlist) # Output: False
但是使用的时候没有提示NameError: name 'exit' is not defined
。以下代码片段的输出让我感到困惑。谁能帮帮我?
for i in range(5):
print(i)
cur=i if i<2 else exit
print(cur)
# Output
0
1
2
3
4
Use exit() or Ctrl-D (i.e. EOF) to exit
我无法从 Python 文档中获取有关 exit
的相关信息,exit([code=None])
除外。
关键字是 python 语法的一部分。它们通常在语句中具有特殊含义(例如 for
、del
、if
...)。这会产生其他后果——例如您不能创建与关键字同名的变量。
builtins 是 callable objects(例如函数或至少类似函数),python 默认在命名空间中提供。内置函数的例子有 sorted
、id
、vars
、...
值得注意的是,exit
是在交互式会话中提供的便利。强烈建议改用 sys.exit
。
exit
是使用交互式控制台时的sys.exit
函数。
很多东西虽然不是关键字但仍然存在(例如 sum
、int
...)。因此您可以绑定到现有名称,但不能绑定到关键字
exit
是 Quitter
class 的实例。 Quitter
class 定义了一个 __repr__
方法,即 returns 当您在 shell 中键入 exit
时看到的字符串。它还定义了一个 __call__
方法。正如当您像函数一样使用 class 时会调用 __init__
,当像函数一样使用实例时会调用 __call__
。因此,exit()
调用__call__
方法,退出程序。
exit
is an Built-in Constants 由 site
模块添加。
The site
module (which is imported automatically during startup,
except if the -S
command-line option is given) adds several constants
to the built-in namespace. They are useful for the interactive
interpreter shell and should not be used in programs.
我了解到 exit
不是 Python 中的关键字,
import keyword
print('exit' in keyword.kwlist) # Output: False
但是使用的时候没有提示NameError: name 'exit' is not defined
。以下代码片段的输出让我感到困惑。谁能帮帮我?
for i in range(5):
print(i)
cur=i if i<2 else exit
print(cur)
# Output
0
1
2
3
4
Use exit() or Ctrl-D (i.e. EOF) to exit
我无法从 Python 文档中获取有关 exit
的相关信息,exit([code=None])
除外。
关键字是 python 语法的一部分。它们通常在语句中具有特殊含义(例如 for
、del
、if
...)。这会产生其他后果——例如您不能创建与关键字同名的变量。
builtins 是 callable objects(例如函数或至少类似函数),python 默认在命名空间中提供。内置函数的例子有 sorted
、id
、vars
、...
值得注意的是,exit
是在交互式会话中提供的便利。强烈建议改用 sys.exit
。
exit
是使用交互式控制台时的sys.exit
函数。
很多东西虽然不是关键字但仍然存在(例如 sum
、int
...)。因此您可以绑定到现有名称,但不能绑定到关键字
exit
是 Quitter
class 的实例。 Quitter
class 定义了一个 __repr__
方法,即 returns 当您在 shell 中键入 exit
时看到的字符串。它还定义了一个 __call__
方法。正如当您像函数一样使用 class 时会调用 __init__
,当像函数一样使用实例时会调用 __call__
。因此,exit()
调用__call__
方法,退出程序。
exit
is an Built-in Constants 由 site
模块添加。
The
site
module (which is imported automatically during startup, except if the-S
command-line option is given) adds several constants to the built-in namespace. They are useful for the interactive interpreter shell and should not be used in programs.