Python 從入門到精通/結構化 Python
如引言中所述,Python 被構想為命令列 Shell 和應用程式開發語言之間的橋樑,因此學習如何使用 Python 命令列 Shell 非常重要。可以透過開啟終端視窗並在提示符處輸入 python 來呼叫 Python Shell。如果安裝了多個版本的 Python,則可能需要版本號作為命令的一部分,例如 python3.2。從版本中進行選擇可能因使用的作業系統和安裝方法而異。
在 Ubuntu Linux 系統上啟動 python3.2 將在終端視窗中建立以下訊息。
Python 3.2.2 (default, Sep 5 2011, 21:17:14)
[GCC 4.6.1] on linux2
鍵入 "help"、"copyright"、"credits" 或 "license" 以獲取更多資訊。
>>>
起始訊息顯示了 Python 版本、一些構建資訊以及四個可用於獲取更多關於 python 資訊的命令。license() 提供了 python 的簡要歷史,包括主要版本的釋出年份以及關於 python 分發和許可協議的詳細資訊。credits() 提供了一條簡短的資訊,感謝支援 python 的組織和個人。copyright() 提供了一個關於 Python 的簡短版權列表。help() 將執行 python 幫助子系統,該子系統主要從幫助字串中提供有關 python 函式的詳細資訊。
本教程後面部分的單獨章節將詳細討論 Python 的 help() 命令。
Python 的預設提示符命令提示符是 >>>。Python 在 >>> 提示符的右側顯示一個游標,應在此處輸入 python 命令。
要退出 Shell 並返回到系統提示符,請鍵入 exit() 或 Ctrl-D。
Shell 本身除了提供用於輸入 python 命令和函式的命令列外,沒有為使用者提供太多功能。Shell 中的編輯功能非常有限。
輸入 Shell 的命令可以透過使用向上箭頭和向下箭頭鍵在命令歷史記錄中向前和向後滾動來呼叫。左右箭頭鍵可用於在編輯當前行時重新定位游標。退格鍵具有破壞性,將刪除游標左側的字元。可以透過按 Insert 鍵在插入模式和覆蓋模式之間切換。Delete 鍵的作用類似於退格鍵,但它刪除的是游標處的字元,而不是游標左側的字元。Home 鍵將游標重新定位到當前行最左側的字元,而 End 鍵將游標重新定位到行尾。按下 Enter 將嘗試執行當前行,無論游標位於何處。請注意,按下 Enter 不會在游標處中斷當前行。
Shell 保留了從每次呼叫 Shell 開始輸入的命令的部分歷史記錄。歷史記錄不會在會話之間保留。
PageUp 選擇歷史記錄列表中的第一個命令進行編輯,而 PageDown 鍵執行編輯最後一個輸入命令的補充功能。
大多數 python 使用者很少使用命令列 Shell 直譯器。它最常見的用途可能是作為計算器。在命令列中輸入的算術表示式將立即計算,並顯示結果。最近一次計算的結果分配給下劃線字元。以下顯示了下劃線字元的使用方法。
>>> 2+2
4
>>> _
4
>>> _*_
16
Python 有兩種基本數值型別:int(整數)和 float(浮點數)。Python 整數可以是任意長度。Python 整數沒有最小或最大(下限或上限),儘管在處理非常長的整數時,處理速度自然會降低。在命令列中,如果輸入的數字沒有小數點,Python 會識別出它是 int,如果包含小數點,則識別出它是 float。Python 會識別 1 是 int,而 1.0 是 float。實數可以轉換為 int,反之亦然,如下所示:float(1) 將整數轉換為 float,而 int(1.1) 將 int 轉換為 float。
32 位 Windows 版 Python 3.2.2 提供了以下有關數值浮點數型別的資訊
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
Python 提供了以下眾所周知且易於理解的算術運算子號。
運算子 符號
冪運算 **
取模 %; 乘法 *; 除法 / (優先順序相同)
加法 +; 減法 - (優先順序相同)
Python 按所示順序遵循這些運算子的典型優先順序。括號內包含的計算具有最高優先順序。當運算的優先順序不受運算子優先順序或括號分組決定時,計算將從左到右執行。
1. 啟動 python 直譯器。注意歡迎螢幕上顯示的版本號。退出 Shell。重新啟動 Shell。嘗試輸入歡迎訊息中列出的不同命令(help、copyright、credits、license)。嘗試一些計算。嘗試除以兩個您預計會產生分數結果的整數(例如,5/2)。注意結果。嘗試各種運算組合,以說服自己運算子的優先順序是可預測的。務必嘗試使用括號。在命令列中輸入 2*(5+。當您不匹配每個左括號和右括號時會發生什麼?
2. 考慮啟動 python 命令列直譯器的其他方法。考慮您偏愛哪種方法以及原因。


Python 指令碼可以在任何文字編輯器中建立,但有一些注意事項。1. 在為 Unix 型別系統編寫指令碼時,通常建議包含 Shebang 行。2. 在某些 Unix 型別環境中,直譯器可能在處理 DOS 型別換行符時遇到問題。
Python 的完整安裝包括一個名為 IDLE 的 IDE。IDLE 的名稱看起來像是某個東西的首字母縮寫,但與 Python 本身一樣,它是一個借自 Monty Python 的名稱,在這種情況下,它是 Monty Python 常規成員 Eric Idle 的姓氏。IDLE 由 Python 的創始人 Guido von Rossum 編寫。
大多數或所有來自官方 python 網站 Python.org 的 Python 版本都包含 IDLE。其他一些 Python 版本(如 IronPython 和 ActivePython)通常不包含它。
您可以從 Shell 或命令視窗啟動 IDLE,但是首選方法是透過作業系統的 GUI 選單啟動 IDLE。預設情況下,IDLE 會開啟兩個視窗:編輯器和 Shell。
IDLE Shell 類似於命令直譯器 Shell,但提供了更多功能。在討論其他功能之前,請注意我們失去了命令直譯器 Shell 的一個更方便的功能,即使用向上和向下箭頭鍵在命令歷史記錄列表中向前和向後滾動。在 IDLE Shell 中,如果要編輯或重新執行先前發出的命令,可以使用 Alt-p 和 Alt-n 在最近的命令列表中滾動。您也可以在視窗中找到先前發出的命令,將游標定位在其上,然後按 Enter 鍵。與命令列 Shell 直譯器不同,IDLE 會保留從會話開始到 Shell 關閉為止 Shell 中所有命令的歷史記錄。
IDLE Shell 和 IDLE 編輯器都支援滑鼠和捲軸,用於在視窗中導航和編輯內容。
以下是 IDLE README 中逐字引用的內容
IDLE is Python's Tkinter-based Integrated DeveLopment Environment. IDLE emphasizes a lightweight, clean design with a simple user interface. Although it is suitable for beginners, even advanced users will find that IDLE has everything they really need to develop pure Python code. IDLE features a multi-window text editor with multiple undo, Python colorizing, and many other capabilities, e.g. smart indent, call tips, and autocompletion. The editor has comprehensive search functions, including searching through multiple files. Class browsers and path browsers provide fast access to code objects from a top level viewpoint without dealing with code folding. There is a Python Shell window which features colorizing and command recall. IDLE executes Python code in a separate process, which is restarted for each Run (F5) initiated from an editor window. The environment can also be restarted from the Shell window without restarting IDLE. This enhancement has often been requested, and is now finally available. The magic "reload/import *" incantations are no longer required when editing and testing a module two or three steps down the import chain. (Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet.) It is possible to interrupt tightly looping user code, even on Windows. Applications which cannot support subprocesses and/or sockets can still run IDLE in a single process. IDLE has an integrated debugger with stepping, persistent breakpoints, and call stack visibility. There is a GUI configuration manager which makes it easy to select fonts, colors, keybindings, and startup options. This facility includes a feature which allows the user to specify additional help sources, either locally or on the web. IDLE is coded in 100% pure Python, using the Tkinter GUI toolkit (Tk/Tcl) and is cross-platform, working on Unix, Mac, and Windows. IDLE accepts command line arguments. Try idle -h to see the options. If you find bugs or have suggestions or patches, let us know about them by using the Python issue tracker: http://bugs.python.org For further details and links, read the Help files and check the IDLE home page at https://python.club.tw/idle/ There is a mail list for IDLE: idle-dev@python.org. You can join at http://mail.python.org/mailman/listinfo/idle-dev
這對許多使用者來說可能是一個足夠的前言。IDLE 的幫助選單提供了關於 IDLE 選單和選項的使用和功能的更多說明資訊,並且此處複製了幫助的全部內容。
[See the end of this file for ** TIPS ** on using IDLE !!]
Click on the dotted line at the top of a menu to "tear it off": a
separate window containing the menu is created.
File Menu:
New Window -- Create a new editing window
Open... -- Open an existing file
Recent Files... -- Open a list of recent files
Open Module... -- Open an existing module (searches sys.path)
Class Browser -- Show classes and methods in current file
Path Browser -- Show sys.path directories, modules, classes
and methods
---
Save -- Save current window to the associated file (unsaved
windows have a * before and after the window title)
Save As... -- Save current window to new file, which becomes
the associated file
Save Copy As... -- Save current window to different file
without changing the associated file
---
Print Window -- Print the current window
---
Close -- Close current window (asks to save if unsaved)
Exit -- Close all windows, quit (asks to save if unsaved)
Edit Menu:
Undo -- Undo last change to current window
(A maximum of 1000 changes may be undone)
Redo -- Redo last undone change to current window
---
Cut -- Copy a selection into system-wide clipboard,
then delete the selection
Copy -- Copy selection into system-wide clipboard
Paste -- Insert system-wide clipboard into window
Select All -- Select the entire contents of the edit buffer
---
Find... -- Open a search dialog box with many options
Find Again -- Repeat last search
Find Selection -- Search for the string in the selection
Find in Files... -- Open a search dialog box for searching files
Replace... -- Open a search-and-replace dialog box
Go to Line -- Ask for a line number and show that line
Show Calltip -- Open a small window with function param hints
Show Completions -- Open a scroll window allowing selection keywords
and attributes. (see '*TIPS*', below)
Show Parens -- Highlight the surrounding parenthesis
Expand Word -- Expand the word you have typed to match another
word in the same buffer; repeat to get a
different expansion
Format Menu (only in Edit window):
Indent Region -- Shift selected lines right 4 spaces
Dedent Region -- Shift selected lines left 4 spaces
Comment Out Region -- Insert ## in front of selected lines
Uncomment Region -- Remove leading # or ## from selected lines
Tabify Region -- Turns *leading* stretches of spaces into tabs
(Note: We recommend using 4 space blocks to indent Python code.)
Untabify Region -- Turn *all* tabs into the right number of spaces
New Indent Width... -- Open dialog to change indent width
Format Paragraph -- Reformat the current blank-line-separated
paragraph
Run Menu (only in Edit window):
Python Shell -- Open or wake up the Python shell window
---
Check Module -- Run a syntax check on the module
Run Module -- Execute the current file in the __main__ namespace
Shell Menu (only in Shell window):
View Last Restart -- Scroll the shell window to the last restart
Restart Shell -- Restart the interpreter with a fresh environment
Debug Menu (only in Shell window):
Go to File/Line -- look around the insert point for a filename
and linenumber, open the file, and show the line
Debugger (toggle) -- Run commands in the shell under the debugger
Stack Viewer -- Show the stack traceback of the last exception
Auto-open Stack Viewer (toggle) -- Open stack viewer on traceback
Options Menu:
Configure IDLE -- Open a configuration dialog. Fonts, indentation,
keybindings, and color themes may be altered.
Startup Preferences may be set, and Additional Help
Sources can be specified.
On MacOS X this menu is not present, use
menu 'IDLE -> Preferences...' instead.
---
Code Context -- Open a pane at the top of the edit window which
shows the block context of the section of code
which is scrolling off the top or the window.
(Not present in Shell window.)
Windows Menu:
Zoom Height -- toggles the window between configured size
and maximum height.
---
The rest of this menu lists the names of all open windows;
select one to bring it to the foreground (deiconifying it if
necessary).
Help Menu:
About IDLE -- Version, copyright, license, credits
IDLE Readme -- Background discussion and change details
---
IDLE Help -- Display this file
Python Docs -- Access local Python documentation, if
installed. Otherwise, access www.python.org.
---
(Additional Help Sources may be added here)
** TIPS **
==========
Additional Help Sources:
Windows users can Google on zopeshelf.chm to access Zope help files in
the Windows help format. The Additional Help Sources feature of the
configuration GUI supports .chm, along with any other filetypes
supported by your browser. Supply a Menu Item title, and enter the
location in the Help File Path slot of the New Help Source dialog. Use
http:// and/or www. to identify external URLs, or download the file and
browse for its path on your machine using the Browse button.
All users can access the extensive sources of help, including
tutorials, available at www.python.org/doc. Selected URLs can be added
or removed from the Help menu at any time using Configure IDLE.
Basic editing and navigation:
Backspace deletes char to the left; DEL deletes char to the right.
Control-backspace deletes word left, Control-DEL deletes word right.
Arrow keys and Page Up/Down move around.
Control-left/right Arrow moves by words in a strange but useful way.
Home/End go to begin/end of line.
Control-Home/End go to begin/end of file.
Some useful Emacs bindings are inherited from Tcl/Tk:
Control-a beginning of line
Control-e end of line
Control-k kill line (but doesn't put it in clipboard)
Control-l center window around the insertion point
Standard Windows bindings may work on that platform.
Keybindings are selected in the Settings Dialog, look there.
Automatic indentation:
After a block-opening statement, the next line is indented by 4 spaces
(in the Python Shell window by one tab). After certain keywords
(break, return etc.) the next line is dedented. In leading
indentation, Backspace deletes up to 4 spaces if they are there. Tab
inserts spaces (in the Python Shell window one tab), number depends on
Indent Width. (N.B. Currently tabs are restricted to four spaces due
to Tcl/Tk issues.)
See also the indent/dedent region commands in the edit menu.
Completions:
Completions are supplied for functions, classes, and attributes of
classes, both built-in and user-defined. Completions are also provided
for filenames.
The AutoCompleteWindow (ACW) will open after a predefined delay
(default is two seconds) after a '.' or (in a string) an os.sep is
typed. If after one of those characters (plus zero or more other
characters) you type a Tab the ACW will open immediately if a possible
continuation is found.
If there is only one possible completion for the characters entered, a
Tab will supply that completion without opening the ACW.
'Show Completions' will force open a completions window. In an empty
string, this will contain the files in the current directory. On a
blank line, it will contain the built-in and user-defined functions and
classes in the current name spaces, plus any modules imported. If some
characters have been entered, the ACW will attempt to be more specific.
If string of characters is typed, the ACW selection will jump to the
entry most closely matching those characters. Entering a Tab will cause
the longest non-ambiguous match to be entered in the Edit window or
Shell. Two Tabs in a row will supply the current ACW selection, as
will Return or a double click. Cursor keys, Page Up/Down, mouse
selection, and the scrollwheel all operate on the ACW.
'Hidden' attributes can be accessed by typing the beginning of hidden
name after a '.'. e.g. '_'. This allows access to modules with
'__all__' set, or to class-private attributes.
Completions and the 'Expand Word' facility can save a lot of typing!
Completions are currently limited to those in the namespaces. Names in
an Edit window which are not via __main__ or sys.modules will not be
found. Run the module once with your imports to correct this
situation. Note that IDLE itself places quite a few modules in
sys.modules, so much can be found by default, e.g. the re module.
If you don't like the ACW popping up unbidden, simply make the delay
longer or disable the extension. OTOH, you could make the delay zero.
You could also switch off the CallTips extension. (We will be adding
a delay to the call tip window.)
Python Shell window:
Control-c interrupts executing command.
Control-d sends end-of-file; closes window if typed at >>> prompt
(this is Control-z on Windows).
Command history:
Alt-p retrieves previous command matching what you have typed.
Alt-n retrieves next.
(These are Control-p, Control-n on the Mac)
Return while cursor is on a previous command retrieves that command.
Expand word is also useful to reduce typing.
Syntax colors:
The coloring is applied in a background "thread", so you may
occasionally see uncolorized text. To change the color
scheme, use the Configure IDLE / Highlighting dialog.
Python default syntax colors:
Keywords orange
Builtins royal purple
Strings green
Comments red
Definitions blue
Shell default colors:
Console output brown
stdout blue
stderr red
stdin black
Other preferences:
The font preferences, keybinding, and startup preferences can
be changed using the Settings dialog.
Command line usage:
Enter idle -h at the command prompt to get a usage message.
Running without a subprocess:
If IDLE is started with the -n command line switch it will run in a
single process and will not create the subprocess which runs the RPC
Python execution server. This can be useful if Python cannot create
the subprocess or the RPC socket interface on your platform. However,
in this mode user code is not isolated from IDLE itself. Also, the
environment is not restarted when Run/Run Module (F5) is selected. If
your code has been modified, you must reload() the affected modules and
re-import any specific items (e.g. from foo import baz) if the changes
are to take effect. For these reasons, it is preferable to run IDLE
with the default subprocess if at all possible.
Extensions:
IDLE contains an extension facility. See the beginning of
config-extensions.def in the idlelib directory for further information.
The default extensions are currently:
FormatParagraph
AutoExpand
ZoomHeight
ScriptBinding
CallTips
ParenMatch
AutoComplete
CodeContext
IDLE 練習
與其試圖闡述或改寫 IDLE 文件中提供的清晰解釋,不如提供一系列旨在讓讀者熟悉 IDLE IDE 的選單項和功能的練習。
1. 從作業系統的 GUI 選單中查詢並開啟 IDLE。嘗試關閉編輯器。請注意,關閉編輯器不會終止 Shell。使用 Shell 中的“檔案|新建視窗”選單項開啟一個新的編輯器視窗。使用相同的選單項,確定您是否可以同時開啟多個編輯器視窗。
2. 現在關閉 Shell。使用 IDLE 編輯器的“視窗|*Python Shell*”選單項重新開啟 Shell。
3. 在 Shell 中輸入一個簡短的程式,例如
for n in range(0,10):
print(n)
在第一行末尾的冒號後務必按 Enter。請注意,IDLE 會自動縮排。您認為是什麼觸發了縮排?
4. 重新輸入該行並故意出錯。會發生什麼?
5. 在 Shell 視窗中找到程式碼的有效副本。使用滑鼠或箭頭將游標(細的閃爍垂直條)定位到讀取 for n in range(0,10): 的行,然後按 Enter。請注意,整個程式碼塊將複製到活動提示符處,您可以在其中對其進行編輯。嘗試透過使用滑鼠選擇程式碼並按 Ctrl-C 複製,然後將其貼上到當前位置來複制相同的程式碼。考慮哪種方法更容易使用。
6. 複製相同的程式碼並將其貼上到編輯器視窗中。使用 IDLE 編輯器的“執行|檢查模組”選單項檢查指令碼。嘗試使用 IDLE 編輯器的“執行|執行模組”選單項或 F5 鍵執行指令碼。您應該發現,為了執行任一操作,您都需要儲存指令碼。有一種方法可以指示 IDLE 編輯器自動儲存指令碼更改。您認為該選項在哪裡?請注意,IDLE 不會建立指令碼的備份副本,但它確實在記憶體中保留了 1000 個撤消步驟。考慮您可以使用的儲存外部審計跟蹤的方法,以便在必要時恢復到程式碼的早期版本。
7. 如果尚未儲存,請將程式碼儲存在文字編輯器中。請注意您是否需要鍵入 .py 副檔名,或者儲存對話方塊是否會自動為您執行此操作。
8. 儲存 Shell 視窗的內容。在 IDLE 編輯器中開啟儲存的內容。你能想到儲存 Shell 視窗內容可能有哪些用途嗎?
9. 透過點選選單頂部虛線處,分離任意下拉選單的副本。關閉下拉選單的浮動副本。考慮一下這是否是一個有用的功能,以及你可能會如何使用它。
10. 比較 Shell 和編輯器中顯示的主選單項。注意,兩者都有七個選單,但編輯器有一個“格式”項,而 Shell 有一個“Shell”項。
11. 嘗試 IDLE 編輯器“格式”選單中的各種選項。您可以將以下程式碼片段剪下並貼上到 IDLE 編輯器中進行練習。
pyramid = [3, 7, 4, 2, 4, 6, 8, 5, 9, 3]
class node(object):
value = 0
left = 0
right = 0
def __init__(self, v, l, r):
self.value = v
self.left = l
self.right = r
l = []
c = 0
r = 0
t = node
for n in pyramid:
t = node(n, 0, 0)
l.append(t)
for t in l:
print(t.value, t.left, t.right)