Python與Perl,C和Java語言等有許多相似之處。不過,也有語言之間有一些明確的區(qū)別。本章的目的是讓你迅速學(xué)習(xí)Python的語法。
第一個Python程序:
交互模式編程:
調(diào)用解釋器不經(jīng)過腳本文件作為參數(shù),顯示以下提示:
1
2
3
4
5
|
$ python Python 2.6.4 ( #1, Nov 11 2014, 13:34:43) [GCC 4.1.2 20120704 (Red Hat 5.6.2-48)] on linux2 Type "help" , "copyright" , "credits" or "license" for more information. >>> |
鍵入下列文字在Python提示符,然后按Enter鍵:
1
|
>>> print "Hello, Python!" ; |
如果您運行的是新的Python版本,那么需要使用打印語句括號像print ("Hello, Python!");。但是在Python版本2.6.4,這將產(chǎn)生以下結(jié)果:
1
|
Hello, Python! |
腳本模式編程:
調(diào)用解釋器及腳本作為參數(shù),并開始執(zhí)行的腳本,并一直持續(xù)到腳本完成。當(dāng)腳本完成時,解釋器不再是活動的。
讓我們在腳本中編寫一個簡單的Python程序。所有的Python文件將具有.py擴(kuò)展。所以,把下面的代碼寫在一個test.py文件。
1
|
print "Hello, Python!" ; |
在這里,我假設(shè)你已經(jīng)在PATH變量中設(shè)置Python解釋器。現(xiàn)在,嘗試如下運行這個程序:
1
|
$ python test .py |
這將產(chǎn)生以下結(jié)果:
1
|
Hello, Python! |
讓我們嘗試另一種方式來執(zhí)行Python腳本。下面是修改后的test.py文件:
1
2
3
|
#!/usr/bin/python print "Hello, Python!" ; |
在這里,假設(shè)Python解釋器在/usr/bin目錄中可用。現(xiàn)在,嘗試如下運行這個程序:
1
2
|
$ chmod +x test .py # This is to make file executable $. /test .py |
這將產(chǎn)生以下結(jié)果:
1
|
Hello, Python! |
Python標(biāo)識符:
Python標(biāo)識符是用來標(biāo)識一個變量,函數(shù),類,模塊或其他對象的名稱。一個標(biāo)識符開始以字母A到Z或a?z或后跟零個或多個字母下劃線(_),下劃線和數(shù)字(0?9)。
Python中標(biāo)識符內(nèi)不允許標(biāo)點符號,如@,$和%。 Python是一種區(qū)分大小寫的編程語言。因此,Manpower 和manpower在Python中是兩個不同的標(biāo)識符。
這里有Python標(biāo)識符命名約定:
- 類名以大寫字母以及所有其它標(biāo)識符以小寫字母。
- 開頭單個前導(dǎo)下劃線的標(biāo)識符表示由該標(biāo)識符約定意思是私有的。
- 開頭兩個前導(dǎo)下劃線的標(biāo)識符表示一個強烈的私有的標(biāo)識符。
- 如果標(biāo)識符末尾還具有兩個下劃線結(jié)束時,該標(biāo)識符是一個語言定義的特殊名稱。
保留字:
下面列出了在Python中的保留字。這些保留字不可以被用作常量或變量,或任何其它標(biāo)識符。所有Python關(guān)鍵字只包含小寫字母。
行和縮進(jìn):
一個程序員學(xué)習(xí)Python時,遇到的第一個需要注意的地方是,不使用括號來表示代碼的類和函數(shù)定義塊或流程控制。代碼塊是由行縮進(jìn),這是嚴(yán)格執(zhí)行表示方式。
在縮進(jìn)位的數(shù)目是可變的,但是在塊中的所有語句必須縮進(jìn)相同的量。在這個例子中,兩個功能塊都很好使用:
1
2
3
4
|
if True : print "True" else : print "False" |
然而,在本實施例中的第二塊將產(chǎn)生一個錯誤:
1
2
3
4
5
6
|
if True : print "Answer" print "True" else : print "Answer" print "False" |
因此,在Python中所有的連續(xù)線縮進(jìn)的空格數(shù)同樣的會結(jié)成塊。以下是各種語句塊中的例子:
注意:不要試圖理解所使用的邏輯或不同的功能。只要確定你明白,即使他們各種模塊無需括號。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
#!/usr/bin/python import sys try : # open file stream file = open (file_name, "w" ) except IOError: print "There was an error writing to" , file_name sys.exit() print "Enter '" , file_finish, print "' When finished" while file_text ! = file_finish: file_text = raw_input ( "Enter text: " ) if file_text = = file_finish: # close the file file .close break file .write(file_text) file .write( "\n" ) file .close() file_name = raw_input ( "Enter filename: " ) if len (file_name) = = 0 : print "Next time please enter something" sys.exit() try : file = open (file_name, "r" ) except IOError: print "There was an error reading file" sys.exit() file_text = file .read() file .close() print file_text |
多行語句:
Python語句通常用一個新行結(jié)束。 但是,Python允許使用續(xù)行字符(\)來表示,該行應(yīng)該繼續(xù)下去(跨行)。例如:
1
2
3
|
total = item_one + \ item_two + \ item_three |
包含在[],{}或()括號內(nèi)的陳述并不需要使用續(xù)行符。例如:
1
2
|
days = [ 'Monday' , 'Tuesday' , 'Wednesday' , 'Thursday' , 'Friday' ] |
Python引號:
Python接受單引號('),雙引號(“)和三(''或”“”)引用,以表示字符串常量,只要是同一類型的引號開始和結(jié)束的字符串。
三重引號可以用于跨越多個行的字符串。例如,所有下列是合法的:
1
2
3
4
|
word = 'word' sentence = "This is a sentence." paragraph = """This is a paragraph. It is made up of multiple lines and sentences.""" |
Python注釋:
一個井號(#),這不是一個字符串文字開頭的注釋。“#”號之后字符和到物理行是注釋的一部分,Python解釋器會忽略它們。
1
2
3
4
|
#!/usr/bin/python # First comment print "Hello, Python!" ; # second comment |
這將產(chǎn)生以下結(jié)果:
1
|
Hello, Python! |
注釋可能會在聲明中表達(dá)或同一行之后:
1
|
name = "Madisetti" # This is again comment |
你可以使用多行注釋如下:
1
2
3
4
|
# This is a comment. # This is a comment, too. # This is a comment, too. # I said that already. |
使用空行:
一行只含有空格,可能帶有注釋,如果是空行那么Python完全忽略它。
在交互式解釋器會話中,必須輸入一個空的物理行終止多行語句。
等待用戶:
程序的下面一行顯示的提示,按回車鍵退出,等待用戶按下回車鍵:
1
2
3
|
#!/usr/bin/python raw_input ( "\n\nPress the enter key to exit." ) |
在這里,“\n\n已”被用來顯示實際行之前創(chuàng)建兩個換行。一旦用戶按下鍵時,程序結(jié)束。這是一個很好的技巧,保持一個控制臺窗口打開,直到用戶完成應(yīng)用程序運行。
在一行中多個語句:
分號( ; ) 允許在單行寫入多條語句,不管語句是否啟動一個新的代碼塊。下面是使用分號示例:
1
|
import sys; x = 'foo' ; sys.stdout.write(x + '\n' ) |
多個語句組作為套件:
一組單獨的語句,在Python單一的代碼塊被稱為序列。復(fù)雜的語句,如if, while, def, and class,那些需要一個標(biāo)題行和套件。
標(biāo)題行開始的聲明(與關(guān)鍵字),并終止與冒號(:)),接著是一個或多個線構(gòu)成該套件。例如:
1
2
3
4
5
6
|
if expression : suite elif expression : suite else : suite |
命令行參數(shù):
我們可能已經(jīng)看到了,比如,很多程序可以運行,它們提供有關(guān)如何運行的一些基本信息。 Python中可以使用 -h 做到這一點:
1
2
3
4
5
6
7
8
9
|
$ python -h usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): -c cmd : program passed in as string (terminates option list) -d : debug output from parser (also PYTHONDEBUG=x) -E : ignore environment variables (such as PYTHONPATH) -h : print this help message and exit [ etc. ] |
您也可以設(shè)定您的腳本,它應(yīng)該以這樣的方式接受各種選項。 命令行參數(shù)是一個高級主題并在以后學(xué)習(xí),當(dāng)您通過其它的Python概念后。