第一個Python程式
交互模式編程
$ python Python 3.3.2 (default, Dec 10 2013, 11:35:01) [GCC 4.6.3] on Linux Type "help", "copyright", "credits", or "license" for more information. >>>
在 Windows 系統上: C:\Users\Administrator>python Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AM D64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>在 Python 提示符下編寫下麵的文本代碼,然後按Enter:
>>> print ("Hello, Python!")
如果你使用的是 Python(Python2.X)的舊版本,在print 函數使用括弧是一個可選項。這將產生以下的結果:
Hello, Python!
腳本編程模式
解釋器調用一個腳本參數開始執行腳本,並一直持續到腳本完成。當腳本完成,解釋器活動失效。
讓我們在腳本中寫一個簡單的 Python 程式。Python檔使用 .py 擴展名。 創建一個檔 test.py 並寫入以下代碼:
print ("Hello, Python!")
假設你已經在 PATH 變數中設置了 Python 解釋器路徑。 現在,試著如下運行這個程式 -
在Linux上執行$ python test.py
Hello, Python!在 Windows 上執行
C:\Python3>Python test.py
Hello, Python!
#!/usr/bin/python3 print ("Hello, Python!")
假設你已經在 /usr/bin目錄安裝好了 Python 解釋器。現在,試著如下運行這個程式 -
$ chmod +x test.py # This is to make file executable $./test.py
Hello, Python!
Python識別字
Python識別字是用來標識變數,函數,類,模組或其他對象的名稱。識別字是以字母A到Z開始或a〜z或後跟零個或多個字母下劃線(_),下劃線和數字(0〜9)。
Python識別字範圍內的不容許有如:@, $ 和 % 符號。Python是一種區分大小寫的編程語言。因此,Manpower 和 manpower 在Python中是兩種不同的識別字。
-
類名稱使用大寫字母。所有其他識別字開始使用小寫字母。
-
開頭使用一個下劃線的識別字表示該識別字是私有的。
-
開始以兩個前導下劃線的識別字表示強烈私有的識別字。
-
如果識別字使用兩個下劃線作為結束時,所述識別字是語言定義的特殊的名字。
保留字
Python 的關鍵字如下列出。這些是保留字,不能把它們作為常量或變數或任何其他識別字名稱。 所有Python的關鍵字僅包含小寫字母。
and | exec | Not |
as | finally | or |
assert | for | pass |
break | from | |
class | global | raise |
continue | if | return |
def | import | try |
del | in | while |
elif | is | with |
else | lambda | yield |
except |
|
|
行和縮進
Python不使用大括弧({})來表示的代碼塊類和函數定義或流程控制。代碼塊由行縮進,這是嚴格執行表示。
在縮進位的數目是可變的,但該塊內的所有語句的縮進量必須相同。 例如 -
if True: print ("True") else: print ("False")
if True: print ("Answer") print ("True") else: print "(Answer") print ("False")
因此,Python中所有連續不換行,同樣數量的空格縮進將形成一個塊。下麵的例子有各種各樣的語句塊 -
注意:不要試圖理解其中的邏輯在這個時候。只要你明白,即使他們不使用括弧在各個模組。
#!/usr/bin/python3 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 = 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語句通常使用一個新行作為結束。但是,Python 允許使用續行字元(\)表示讓行可以連續下去。例如-
total = item_one + \ item_two + \ item_three
語句中包含 [], {}, 或() 括弧內不需要使用續行字元。 例如−
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
在Python的引號
word = 'word' sentence = "This is a sentence." paragraph = """This is a paragraph. It is made up of multiple lines and sentences."""
Python中的注釋
哈希符號(#)這是一個字元作為注釋的開頭。在#之後到行末的所有字元都是注釋的一部分,Python解釋器會忽略它們。
#!/usr/bin/python3 # First comment print ("Hello, Python!") # second comment
Hello, Python!
name = "Madisetti" # This is again comment
# This is a comment. # This is a comment, too. # This is a comment, too. # I said that already.
使用空行
等待用戶
#!/usr/bin/python3 input("\n\nPress the enter key to exit.")
在這裏,“\n\n”是用來顯示實際行之前創建的兩條新行。一旦用戶按下鍵時,程式就結束。 這是一個很好的技巧,以保持控制臺窗口打開,直到用戶來指定終止應用程式運行。
在一行多條語句
import sys; x = 'foo'; sys.stdout.write(x + '\n')
多重聲明組為套件
一組單獨的語句,它們使單一代碼塊化在Python稱為套件。複雜的語句,如 if, while, def, 和 class 需要一個標頭行和一個套件。
if expression : suite elif expression : suite else : suite
命令行參數
$ 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. ]
您也可以在這樣的,它應該接受各種選擇的方式編寫腳本。命令行參數是一個高級的主題,當你已經學習了Python概念後,其餘部分的內容我們將在接下來的章節中學習。