0
点赞
收藏
分享

微信扫一扫

Python教程——2.交互式 Python


在 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 交互模式下使用的提示。 要离开解释器并返回外壳,我们可以输入 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 © 2001-2016 Python Software Foundation.

All Rights Reserved.

Copyright © 2000 BeOpen.com.

All Rights Reserved.

Copyright © 1995-2001 Corporation for National Research Initiatives.

All Rights Reserved.

Copyright © 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 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 whosename

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


我们可以定义自己的类,函数或使用控制流结构。 我们一定不要忘记缩进代码。 要完成所有这些代码块,我们键入,输入两次键。


import os
os.getcwd()
‘/home/vronskij/programming/python’
os.system(‘ls’)
command_line_arguments.py read_input.py
0
在这里,我们导入os模块并与操作系统进行交互。


最后,我们要退出解释器。 我们可以通过几种方式退出解释器:

Ctrl + D

exit()

我们还可以以编程方式退出解释器。


raise SystemExit
$
要么



import sys
sys.exit()
$
解释器已退出。


Python 之禅

Python 的 Zen 是一套有关如何编写良好的 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 交互式解释器。

如果想学习更多的python教程,不想再体验一次自学时找不到资料,没人解答问题,坚持几天便放弃的感受的话,可以常去一些技术论坛、群。多和别人交流,探讨一些技术上的问题。在这里向大家推荐(785128166)、群,有技术大牛解惑答疑



举报

相关推荐

0 条评论