💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 交互式 Python > 原文: [http://zetcode.com/lang/python/interactivepython/](http://zetcode.com/lang/python/interactivepython/) 在 Python 编程教程的这一部分中,我们讨论交互式 Python 解释器。 Python 代码可以通过两种基本方式启动。 作为脚本或在交互式解释器中。 ```py #!/usr/bin/env python # first.py print("The Python tutorial") ``` 这是一个小型 Python 脚本的示例。 它是从 UNIX Shell 启动的。 ```py $ ./first.py The Python tutorial ``` ## 交互解释器 运行 Python 代码的另一种方法是交互式 Python 解释器。 Python 解释器对于我们的探索非常有用。 当我们快速想要测试 Python 语言的一些基本功能并且不想编写整个脚本时。 为了获得交互式解释器,我们在最喜欢的 shell 上执行 Python 命令。 ```py $ 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 交互模式下使用的提示。 要离开解释器并返回外壳,我们可以输入 `Ctrl + D` 或`quit()`。 键入 `Ctrl + L` 将清除 Python 解释器的屏幕。 现在我们可以查询一些有用的信息。 ```py >>> 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 开发的组织的一些信息。 ```py >>> 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 的一些帮助。 ```py >>> help Type help() for interactive help, or help(object) for help about object. >>> ``` 我们可以通过两种方式使用该命令。 我们可以获取有关特定对象的帮助,或者进入交互式帮助模式。 例如,如果我们键入`help(True)`,我们将获得有关`bool`对象的一些信息。 ```py 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()`,将获得解释器的交互式帮助模式。 ```py >>> 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 http://docs.python.org/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 编程语言中可用关键字的列表。 ```py 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`命令。 ```py 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 解释器的实际示例。 ```py >>> 2 + 4 6 >>> 5 * 56 280 >>> 5 - 45 -40 >>> ``` Python 解释器可以用作计算器。 立即执行每个表达式,结果显示在屏幕上。 ```py >>> a = 3 >>> b = 4 >>> a**b 81 >>> a == b False >>> a < b True >>> ``` 我们可以定义变量并对其执行操作。 ```py >>> 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__`字符串,我们可以获得有关特定功能的帮助。 ```py >>> 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()`命令显示我们当前的本地名称空间。 ```py >>> 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__'} ``` 我们可以看到我们先前导入的随机模块。 ```py >>> class Car: ... pass ... >>> def function(): ... pass ... >>> for i in range(5): ... print(i) ... 0 1 2 3 4 >>> ``` 我们可以定义自己的类,函数或使用控制流结构。 我们一定不要忘记缩进代码。 要完成所有这些代码块,我们键入`,输入两次`键。 ```py >>> import os >>> os.getcwd() '/home/vronskij/programming/python' >>> os.system('ls') command_line_arguments.py read_input.py 0 ``` 在这里,我们导入`os`模块并与操作系统进行交互。 最后,我们要退出解释器。 我们可以通过几种方式退出解释器: * `Ctrl + D` * `exit()` 我们还可以以编程方式退出解释器。 ```py >>> raise SystemExit $ ``` 要么 ```py >>> import sys >>> sys.exit() $ ``` 解释器已退出。 ## Python 之禅 Python 的 Zen 是一套有关如何编写良好的 Python 代码的规则。 它以某种方式反映了语言的哲学。 ```py >>> 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 交互式解释器。