Python語法(一)

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章