Python 基礎文法
Python 語言與 Perl,C 和 Java 等語言有許多相似之處。但是,也存在一些差異。
在本章中我們将來學習 Python 的基礎文法,讓你快速學會 Python 程式設計。
Python學習概況圖
第一個 Python 程式
互動式程式設計
互動式程式設計不需要建立腳本檔案,是通過 Python 解釋器的互動模式進來編寫代碼。
linux上你隻需要在指令行中輸入 Python 指令即可啟動互動式程式設計,提示視窗如下:
1
2
3
4
5
<code>$ python</code>
<code>Python </code><code>2.7</code><code>.</code><code>9</code> <code>(default, Apr </code><code>2</code> <code>2015</code><code>, </code><code>15</code><code>:</code><code>33</code><code>:</code><code>21</code><code>) </code>
<code>[GCC </code><code>4.9</code><code>.</code><code>2</code><code>] on linux2</code>
<code>Type</code> <code>"help"</code><code>, </code><code>"copyright"</code><code>, </code><code>"credits"</code> <code>or</code> <code>"license"</code> <code>for</code> <code>more information.</code>
<code>>>></code>
Window下CMD預設的互動式程式設計用戶端,提示視窗如下:
在 python 提示符中輸入以下文本資訊,然後按 Enter 鍵檢視運作效果:
<code>>>> </code><code>print</code> <code>"Hello, Python!"</code><code>;</code>
在 Python 2.7.9 版本中,以上執行個體輸出結果如下:
<code>Hello, Python!</code>
腳本式程式設計
通過腳本參數調用解釋器開始執行腳本,直到腳本執行完畢。當腳本執行完成後,解釋器不再有效。
讓我們寫一個簡單的 Python 腳本程式。所有 Python 檔案将以 .py 為擴充名。将以下的源代碼拷貝至 test.py 檔案中。
<code>print</code> <code>"Hello, Python!"</code><code>;</code>
這裡,假設你已經設定了 Python 解釋器 PATH 變量。使用以下指令運作程式:
<code>$ python test.py</code>
輸出結果:
讓我們嘗試另一種方式來執行 Python 腳本。修改 test.py 檔案,如下所示:
<code>#!/usr/bin/python</code>
這裡,假定您的Python解釋器在/usr/bin目錄中,使用以下指令執行腳本:
<code>$ chmod </code><code>+</code><code>x test.py </code><code># 腳本檔案添加可執行權限</code>
<code>$ .</code><code>/</code><code>test.py</code>
Python 辨別符
在 Python 裡,辨別符有字母、數字、下劃線組成。
在 Python 中,所有辨別符可以包括英文、數字以及下劃線(_),但不能以數字開頭。
Python 中的辨別符是區分大小寫的。
以下劃線開頭的辨別符是有特殊意義的。以單下劃線開頭 _foo 的代表不能直接通路的類屬性,需通過類提供的接口進行通路,不能用 from xxx import * 而導入;
以雙下劃線開頭的 __foo 代表類的私有成員;以雙下劃線開頭和結尾的 __foo__ 代表 Python 裡特殊方法專用的辨別,如 __init__() 代表類的構造函數。
Python 可以同一行顯示多條語句,方法是用分号 ; 分開,如:
<code>>>> </code><code>print</code> <code>'hello'</code><code>;</code><code>print</code> <code>'runoob'</code><code>;</code>
<code>hello</code>
<code>runoob</code>
Python 保留字元
下面的清單顯示了在Python中的保留字。這些保留字不能用作常數或變數,或任何其他辨別符名稱。
所有 Python 的關鍵字隻包含小寫字母。
and
exec
not
assert
finally
or
break
for
pass
class
from
continue
global
raise
def
if
return
del
import
try
elif
in
while
else
is
with
except
lambda
yield
行和縮進
學習 Python 與其他語言最大的差別就是,Python 的代碼塊不使用大括号 {} 來控制類,函數以及其他邏輯判斷。python 最具特色的就是用縮進來寫子產品。
縮進的空白數量是可變的,但是所有代碼塊語句必須包含相同的縮進空白數量,這個必須嚴格執行。如下所示:
<code>if</code> <code>True</code><code>:</code>
<code> </code><code>print</code> <code>"True"</code>
<code>else</code><code>:</code>
<code> </code><code>print</code> <code>"False"</code>
以下代碼将會執行錯誤:
6
7
8
9
10
<code># -*- coding: UTF-8 -*-</code>
<code># 檔案名:test.py</code>
<code> </code><code>if</code> <code>True</code><code>:</code>
<code> </code><code>print</code> <code>"Answer"</code>
<code> </code><code># 沒有嚴格縮進,在執行時會報錯</code>
執行以上代碼,會出現如下錯誤提醒:
<code>$ python test.py </code>
<code> </code><code>File</code> <code>"test.py"</code><code>, line </code><code>5</code>
<code> </code><code>if</code> <code>True</code><code>:</code>
<code> </code><code>^</code>
<code>IndentationError: unexpected indent</code>
IndentationError: unexpected indent 錯誤是 python 編譯器是在告訴你"Hi,老兄,你的檔案裡格式不對了,可能是tab和空格沒對齊的問題",所有 python 對格式要求非常嚴格。
如果是 IndentationError: unindent does not match any outer indentation level錯誤表明,你使用的縮進方式不一緻,有的是 tab 鍵縮進,有的是空格縮進,改為一緻即可。
是以,在 Python 的代碼塊中必須使用相同數目的行首縮進空格數。
建議你在每個縮進層次使用 單個制表符 或 兩個空格 或 四個空格 , 切記不能混用
多行語句
Python語句中一般以新行作為為語句的結束符。
但是我們可以使用斜杠( \)将一行的語句分為多行顯示,如下所示:
<code>total </code><code>=</code> <code>item_one </code><code>+</code> <code>\</code>
<code> </code><code>item_two </code><code>+</code> <code>\</code>
<code> </code><code>item_three</code>
語句中包含 [], {} 或 () 括号就不需要使用多行連接配接符。如下執行個體:
<code>days </code><code>=</code> <code>[</code><code>'Monday'</code><code>, </code><code>'Tuesday'</code><code>, </code><code>'Wednesday'</code><code>,</code>
<code> </code><code>'Thursday'</code><code>, </code><code>'Friday'</code><code>]</code>
Python 引号
Python 可以使用引号( ' )、雙引号( " )、三引号( ''' 或 """ ) 來表示字元串,引号的開始與結束必須的相同類型的。
其中三引号可以由多行組成,編寫多行文本的快捷文法,常用于文檔字元串,在檔案的特定地點,被當做注釋。
<code>word </code><code>=</code> <code>'word'</code>
<code>sentence </code><code>=</code> <code>"這是一個句子。"</code>
<code>paragraph </code><code>=</code> <code>"""這是一個段落。</code>
<code>包含了多個語句"""</code>
Python注釋
python中單行注釋采用 # 開頭。
<code># 第一個注釋</code>
<code>print</code> <code>"Hello, Python!"</code><code>; </code><code># 第二個注釋</code>
注釋可以在語句或表達式行末:
<code>name </code><code>=</code> <code>"Madisetti"</code> <code># 這是一個注釋</code>
python 中多行注釋使用三個單引号(''')或三個雙引号(""")。
11
12
13
<code>'''</code>
<code>這是多行注釋,使用單引号。</code>
<code>"""</code>
<code>這是多行注釋,使用雙引号。</code>
Python空行
函數之間或類的方法之間用空行分隔,表示一段新的代碼的開始。類和函數入口之間也用一行空行分隔,以突出函數入口的開始。
空行與代碼縮進不同,空行并不是Python文法的一部分。書寫時不插入空行,Python解釋器運作也不會出錯。但是空行的作用在于分隔兩段不同功能或含義的代碼,便于日後代碼的維護或重構。
記住:空行也是程式代碼的一部分。
等待使用者輸入
下面的程式執行後就會等待使用者輸入,按Enter鍵後就會退出:
<code>raw_input</code><code>(</code><code>"\n\nPress the enter key to exit."</code><code>)</code>
以上代碼中 ,"\n\n"在結果輸出前會輸出兩個新的空行。一旦使用者按下 enter(回車) 鍵退出,其它鍵顯示。
同一行顯示多條語句
Python可以在同一行中使用多條語句,語句之間使用分号(;)分割,以下是一個簡單的執行個體:
<code>import</code> <code>sys; x </code><code>=</code> <code>'runoob'</code><code>; sys.stdout.write(x </code><code>+</code> <code>'\n'</code><code>)</code>
執行以上代碼,輸入結果為:
Print 輸出
print 預設輸出是換行的,如果要實作不換行需要在變量末尾加上逗号:
14
15
16
<code>x</code><code>=</code><code>"a"</code>
<code>y</code><code>=</code><code>"b"</code>
<code># 換行輸出</code>
<code>print</code> <code>x</code>
<code>print</code> <code>y</code>
<code>print</code> <code>'---------'</code>
<code># 不換行輸出</code>
<code>print</code> <code>x,</code>
<code>print</code> <code>y,</code>
<code>以上執行個體執行結果為:</code>
<code>a</code>
<code>b</code>
<code>-</code><code>-</code><code>-</code><code>-</code><code>-</code><code>-</code><code>-</code><code>-</code><code>-</code>
<code>a b</code>
多個語句構成代碼組
縮進相同的一組語句構成一個代碼塊,我們稱之代碼組。
像if、while、def和class這樣的複合語句,首行以關鍵字開始,以冒号( : )結束,該行之後的一行或多行代碼構成代碼組。
我們将首行及後面的代碼組稱為一個子句(clause)。
如下執行個體:
<code>if</code> <code>expression : </code>
<code> </code><code>suite </code>
<code>elif</code> <code>expression : </code>
<code> </code><code>suite </code>
<code>else</code> <code>: </code>
<code> </code><code>suite</code>
指令行參數
很多程式可以執行一些操作來檢視一些基本資訊,Python 可以使用 -h 參數檢視各參數幫助資訊:
<code>$ python </code><code>-</code><code>h </code>
<code>usage: python [option] ... [</code><code>-</code><code>c cmd | </code><code>-</code><code>m mod | </code><code>file</code> <code>| </code><code>-</code><code>] [arg] ... </code>
<code>Options </code><code>and</code> <code>arguments (</code><code>and</code> <code>corresponding environment variables): </code>
<code>-</code><code>c cmd : program passed </code><code>in</code> <code>as string (terminates option </code><code>list</code><code>) </code>
<code>-</code><code>d : debug output </code><code>from</code> <code>parser (also PYTHONDEBUG</code><code>=</code><code>x) </code>
<code>-</code><code>E : ignore environment variables (such as PYTHONPATH) </code>
<code>-</code><code>h : </code><code>print</code> <code>this </code><code>help</code> <code>message </code><code>and</code> <code>exit </code>
<code> </code>
<code>[ etc. ]</code>
本文轉自 運維小當家 51CTO部落格,原文連結:http://blog.51cto.com/solin/1946199,如需轉載請自行聯系原作者