Python语法(一)

来源:互联网 发布:手机淘宝不能分期付款 编辑:程序博客网 时间:2024/04/30 01:32

1.两种解释器

    CPython由C写成;

    Jython由Java写成 ,特点包括

         只要有 Java 虚拟机, 就能运行Jython
         拥有访问 Java 包与类库的能力
         为 Java 开发环境提供了脚本引擎
         能够很容易的测试 Java 类库
         提供访问 Java 原生异常处理的能力
         继承了 JavaBeans 特性和内省能力
         鼓励 Python 到Java 的开发(反之亦然)
         GUI 开发人员可以访问 Java 的 AWT/Swing 库
         利用了 Java 原生垃圾收集器(CPython 未实现此功能)

2.交互式解释器

    >>> primary prompt:expecting the next Python statement

    ...secondary prompt:indicates that the interpreter is waiting for additional input to complete the current statement

主提示符下,'''表示要输入多行

次提示符下,输入if statement 回车后,缩进 然后输入执行语句 最后空行回车表示输入完成

3.print用法

    >>>print variable  #输出 variable content

    >>>variables  #输出 'variable content'

    >>>_  #last evaluated expression

    logfile = open('/tmp/mylog.txt', 'a')
    print >> logfile, 'Fatal error: invalid input!' #redirect output to file named logfile
    logfile.close()

    >>> user = raw_input('Enter login name: ')#built-in function to obtain user input from command line
    Enter login name: root
    >>> print 'Your login is:', user
    Your login is: root    # comma seperate two variables

    >>>print"%s words %d"   %("python",10)

    循环中,print item会为每一个item添加换行符,而print item, 则会用空格代替换行

4.Lists and Tuples

lists and tuples can store different types of objects.

Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed. Tuples are
enclosed in parentheses ( ( ) ) and cannot be updated (although their contents may be). Tuples can be thought of for now as “read-only” lists.

>>> aList = [1, 2, 3, 4]
>>> aList
[1, 2, 3, 4]
>>> aList[0]
1
>>> aList[2:]
[3, 4]
>>> aList[:3]
[1, 2, 3]
>>> aList[1] = 5
>>> aList
[1, 5, 3, 4]
Slice access to a tuple is similar, except it cannot be modified:
>>> aTuple = ('robots', 77, 93, 'try')
>>> aTuple
('robots', 77, 93, 'try')
>>> aTuple[:3]
('robots', 77, 93)
>>> aTuple[1] = 5
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment

 

0 0
原创粉丝点击