Python3基本文法,
編碼
預設情況下,Python3源檔案以utf-8編碼,所有字串都是unicode字串,也可以為源檔案指定編碼。
# -*- coding: cp-1252 -*-
標識符
- 第一個字元必須是字母表中字母或底線'_'。
- 標識符的其他的部分有字母、數字和底線組成。
- 標識符對大小寫敏感。
python保留字
保留字即關鍵字,我們不能把它們用作任何標識符名稱。Python的標準庫提供了一個keyword module,可以輸出目前的版本的所有關鍵字:
>>> import keyword>>> keyword.kwlist['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
注釋
Python中單行注釋以#開頭,多行注釋用三個單引號(''')或者三個雙引號(""")將注釋括起來。
行與縮排
python最具特色的就是使用縮排來表示代碼塊。縮排的空格數是可變的,但是同一個代碼塊的語句必須包含相同的縮排空格數。
資料類型
python中數有四種類型:整數、長整數、浮點數和複數。
- 整數, 如 1
- 長整數 是比較大的整數
- 浮點數 如 1.23、3E-2
- 複數 如 1 + 2j、 1.1 + 2.2j
字串
- python中單引號和雙引號使用完全相同。
- 使用三引號('''或""")可以指定一個多行字串。
- 轉義符 '\'
- 自然字串, 通過在字串前加r或R。 如 r"this is a line with \n" 則\n會顯示,並不是換行。
- python允許處理unicode字串,加首碼u或U, 如 u"this is an unicode string"。
- 字串是不可變的。
- 按字面意義級聯字串,如"this " "is " "string"會被自動轉換為this is string。