交互式 Python
最后修改于 2023 年 10 月 18 日
在本 Python 编程教程中,我们将讨论交互式 Python 解释器。
Python 代码可以通过两种基本方式启动。 作为脚本或在交互式解释器中。
#!/usr/bin/env python
# first.py
print("The Python tutorial")
这是一个小型 Python 脚本的示例。 它从 UNIX shell 启动。
$ ./first.py The Python tutorial
交互式解释器
运行 Python 代码的另一种方法是交互式 Python 解释器。 Python 解释器对我们的探索非常有用。 当我们想快速测试 Python 语言的一些基本功能,并且不想编写整个脚本时。 要获取交互式解释器,我们在我们喜欢的 shell 上执行 Python 命令。
$ python3 Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
这是 Python 解释器的欢迎消息。 我们在机器上看到了 Python 的版本。 在我们的例子中是 Python 3.5.2。 ">>>" 是 Python 交互模式中使用的提示符。 要退出解释器并返回 shell,我们可以键入 Ctrl+D 或 quit。 键入 Ctrl+L 清除 Python 解释器的屏幕。
现在我们可以查询一些有用的信息。
>>> credits
Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
for supporting Python development. See www.python.org for more information.
如果我们键入 credits,我们会获得有关参与 Python 开发的组织的一些信息。
>>> copyright Copyright (c) 2001-2016 Python Software Foundation. All Rights Reserved. Copyright (c) 2000 BeOpen.com. All Rights Reserved. Copyright (c) 1995-2001 Corporation for National Research Initiatives. All Rights Reserved. Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam. All Rights Reserved.
copyright 命令给出 Python 编程语言的版权。
license 命令提供了有关 Python 许可证的几页内容。
获取帮助
help 命令提供了一些关于 Python 的帮助。
>>> help Type help() for interactive help, or help(object) for help about object. >>>
我们可以通过两种方式使用该命令。 我们可以获取有关特定对象的一些帮助,或者我们进入交互式帮助模式。
例如,如果我们键入 help(True),我们会获得有关 bool 对象的一些信息。
Help on bool object: class bool(int) | bool(x) -> bool | | Returns True when the argument x is true, False otherwise. | The builtins True and False are the only two instances of the class bool. | The class bool is a subclass of the class int, and cannot be subclassed. | | Method resolution order: | bool | int | object | | Methods defined here: | | __and__(...) | x.__and__(y) <==> x&y ...
如果主题超过一页,我们可以使用箭头滚动它。 如果要退出该主题,请按 q 键。
如果我们键入 help,我们将获得解释器的交互式帮助模式。
>>> help() Welcome to Python 3.5's help utility! If this is your first time using Python, you should definitely check out the tutorial on the Internet at https://docs.pythonlang.cn/3.5/tutorial/. Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit". To get a list of available modules, keywords, symbols, or topics, type "modules", "keywords", "symbols", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose name or summary contain a given string such as "spam", type "modules spam". help>
要退出帮助模式并返回解释器,我们使用 quit 命令。
keywords 命令给出了 Python 编程语言中可用关键字的列表。
help> keywords Here is a list of the Python keywords. Enter any keyword to get more help. False def if raise None del import return True elif in try and else is while as except lambda with assert finally nonlocal yield break for not class from or continue global pass
如果我们键入任何关键字,我们将获得有关它的帮助。
modules 命令给出了可用模块的列表。 同样,键入模块的名称将提供额外的帮助。
最后,我们有 topics 命令。
help> topics Here is a list of available topics. Enter any topic name to get more help. ASSERTION DELETION LOOPING SHIFTING ASSIGNMENT DICTIONARIES MAPPINGMETHODS SLICINGS ATTRIBUTEMETHODS DICTIONARYLITERALS MAPPINGS SPECIALATTRIBUTES ATTRIBUTES DYNAMICFEATURES METHODS SPECIALIDENTIFIERS AUGMENTEDASSIGNMENT ELLIPSIS MODULES SPECIALMETHODS BASICMETHODS EXCEPTIONS NAMESPACES STRINGMETHODS BINARY EXECUTION NONE STRINGS BITWISE EXPRESSIONS NUMBERMETHODS SUBSCRIPTS BOOLEAN FLOAT NUMBERS TRACEBACKS CALLABLEMETHODS FORMATTING OBJECTS TRUTHVALUE CALLS FRAMEOBJECTS OPERATORS TUPLELITERALS CLASSES FRAMES PACKAGES TUPLES CODEOBJECTS FUNCTIONS POWER TYPEOBJECTS COMPARISON IDENTIFIERS PRECEDENCE TYPES COMPLEX IMPORTING PRIVATENAMES UNARY CONDITIONAL INTEGER RETURNING UNICODE CONTEXTMANAGERS LISTLITERALS SCOPING CONVERSIONS LISTS SEQUENCEMETHODS DEBUGGING LITERALS SEQUENCES
topics 命令给出了关于 Python 编程语言的主题列表。 在这里我们可以找到一些有用的信息。
Python 代码
接下来,我们有一些 Python 解释器的实际示例。
>>> 2 + 4 6 >>> 5 * 56 280 >>> 5 - 45 -40 >>>
Python 解释器可以用作计算器。 每个表达式都会立即执行,结果会显示在屏幕上。
>>> a = 3 >>> b = 4 >>> a**b 81 >>> a == b False >>> a < b True >>>
我们可以定义变量并对它们执行操作。
>>> import random >>> dir(random) ['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '_acos', '_ceil', '_cos', '_e', '_exp', '_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'uniform', 'vonmisesvariate', 'weibullvariate'] >>>
在这里,我们导入了一个随机模块。 使用 dir 函数,我们进一步探索随机模块。
借助特殊的 __doc__ 字符串,我们可以获得关于特定函数的帮助。
>>> print(random.seed.__doc__)
Initialize internal state from hashable object.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If a is not None or an int or long, hash(a) is used instead.
>>>
locals 命令显示我们当前的本地命名空间。
>>> locals()
{'random': <module 'random' from '/usr/lib/python3.5/random.py'>, '__spec__': None,
'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__builtins__': <module 'builtins' (built-in)>, '__doc__': None, '__name__': '__main__'}
我们可以看到我们之前导入的随机模块。
>>> class Car: ... pass ... >>> def function(): ... pass ... >>> for i in range(5): ... print(i) ... 0 1 2 3 4 >>>
我们可以定义我们自己的类、函数或使用控制流结构。 我们不能忘记缩进代码。 要完成代码的每个块,我们键入两次 Enter 键。
>>> import os
>>> os.getcwd()
'/home/vronskij/programming/python'
>>> os.system('ls')
command_line_arguments.py read_input.py
0
在这里,我们导入 os 模块并与操作系统交互。
最后,我们要退出解释器。 我们可以通过几种方式退出解释器
- Ctrl+D
- quit()
我们也可以通过编程方式退出解释器。
>>> raise SystemExit $
或
>>> import sys >>> sys.exit() $
解释器已退出。
Python 之禅
Python 之禅是一组关于如何编写良好 Python 代码的规则。 它在某种程度上反映了该语言的哲学。
>>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
可以通过启动 import this 来阅读这些规则。
在本章中,我们研究了 Python 交互式解释器。