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://www.pythonlang.cn/idle/ There is a mail list for IDLE: [email protected]. 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)