python脚本例子_Python 教程(二)认识交互式Python

02a61e57b12cb6d1529e82b0fd353355.gif

交互式Python,就是通过执行python命令进入到对应的解释器中进行输入指令,python解释器执行,执行完产生对应结果以及指令要完成的动作。Python代码可以通过两种基本方式启动。脚本或交互式解释器。

通过脚本进行操作的代码例子。

#!/usr/bin/env python# first.pyprint("The Python tutorial")

上面的执行步骤就是一个脚本文件。然后通过执行该对应的脚本文件执行。

$ ./first.py The Python tutorial

下面来看一下交互式解释器。

一、交互式解释器

运行Python代码的另一种方式是交互式Python解释器。Python解释器对我们的探索非常有用。当我们快速地想要测试Python语言的一些基本功能而又不想编写整个脚本时。为了获得交互式解释器,我们在最喜欢的shell上执行Python命令。

$ python3Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linuxType "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开发的组织的信息
>>> copyrightCopyright (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的帮助。
>>> helpType 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 outthe 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 writingPython programs and using Python modules.  To quit this help utility andreturn 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 comeswith a one-line summary of what it does; to list the modules whose nameor summary contain a given string such as "spam", type "modules spam".help>

要离开帮助模式并返回到解释器,我们使用quit命令。

下面使用keywords命令给出了Python编程语言中可用关键字的列表。

help> keywordsHere is a list of the Python keywords.  Enter any keyword to get more help.False               def                 if                  raiseNone                del                 import              returnTrue                elif                in                  tryand                 else                is                  whileas                  except              lambda              withassert              finally             nonlocal            yieldbreak               for                 not                 class               from                or                  continue            global              pass

如果我们键入任何关键字,我们会得到一些帮助。

modules命令提供可用模块的列表。同样,输入模块的名称将提供额外的帮助。

最后,我们有topics 命令。

help> topicsHere is a list of available topics.  Enter any topic name to get more help.ASSERTION           DELETION            LOOPING             SHIFTINGASSIGNMENT          DICTIONARIES        MAPPINGMETHODS      SLICINGSATTRIBUTEMETHODS    DICTIONARYLITERALS  MAPPINGS            SPECIALATTRIBUTESATTRIBUTES          DYNAMICFEATURES     METHODS             SPECIALIDENTIFIERSAUGMENTEDASSIGNMENT ELLIPSIS            MODULES             SPECIALMETHODSBASICMETHODS        EXCEPTIONS          NAMESPACES          STRINGMETHODSBINARY              EXECUTION           NONE                STRINGSBITWISE             EXPRESSIONS         NUMBERMETHODS       SUBSCRIPTSBOOLEAN             FLOAT               NUMBERS             TRACEBACKSCALLABLEMETHODS     FORMATTING          OBJECTS             TRUTHVALUECALLS               FRAMEOBJECTS        OPERATORS           TUPLELITERALSCLASSES             FRAMES              PACKAGES            TUPLESCODEOBJECTS         FUNCTIONS           POWER               TYPEOBJECTSCOMPARISON          IDENTIFIERS         PRECEDENCE          TYPESCOMPLEX             IMPORTING           PRIVATENAMES        UNARYCONDITIONAL         INTEGER             RETURNING           UNICODECONTEXTMANAGERS     LISTLITERALS        SCOPING             CONVERSIONS         LISTS               SEQUENCEMETHODS     DEBUGGING           LITERALS            SEQUENCES
topics命令提供有关Python编程语言的主题列表。在这里我们可以找到一些有用的信息。

三、使用解释器进行python代码练习

算数运算(+,-,*,/)的操作

>>> 2 + 46>>> 5 * 56280>>> 5 - 45-40>>> 

Python解释器可以用作计算器。每个表达式立即执行,结果显示在屏幕上。

>>> a = 3>>> b = 4>>> a**b81>>> a == bFalse>>> a < bTrue>>>

上面的代码是通过定义变量来进行算术运算操作。

>>> 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': 'random' from '__package__': None, '__loader__': '_frozen_importlib.BuiltinImporter'>, '__builtins__': 'builtins' (built-in)>, 

我们可以看到前面导入的random模块.

>>> class Car:...   pass... >>> def function():...   pass... >>> for i in range(5):...   print(i)... 01234>>>

我们可以定义自己的类、函数或使用控制流结构。我们不能忘记缩进代码。为了完成这些代码块,我们键入两次Enter key。

>>> import os>>> os.getcwd()'/home/vronskij/programming/python'>>> os.system('ls')command_line_arguments.py  read_input.py0

在上面这个代码,我们导入os模块并与操作系统交互。

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

  • Ctrl+D

  • quit()

我们也可以通过编程的方式退出解释器。

>>> raise SystemExit$

或者

>>> import sys>>> sys.exit()$

解释器退出。

四、python的禅宗

Python的禅宗是一组如何编写好的Python代码的规则。它在某种程度上反映了这种语言的哲学。

可以通过启动import this来读取规则。
>>> import thisThe Zen of Python, by Tim PetersBeautiful 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!

总结:在实际开发的过程中都是使用脚本方式来进行开发的,这种解释执行的方式主要用于检索python的一些模块以及一些对应的帮助等等。主要方便于练习使用。真正项目中都是脚本的方式进行开发的。建议初学者也多接触交互式。这样能够加深代码的记忆。

2ac9a1b7c6c201aa60f3841b0d7f87a1.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值