Python Beginner to Expert/Structured Python< Python Beginner to Expert
Starting the shellEdit
As suggested in the introduction, Python was conceived as a bridge between a command shell and an application development language, so it's important to learn how to use the Python command shell. The Python shell can be invoked by opening a terminal window and entering the word python at the prompt. If more than one version of Python is installed, the version number may be required as part of the command, for example python3.2. Selecting from versions may vary depending on the OS used and the method of installation.
Starting python3.2 on an Ubuntu Linux system will create the following messages on the terminal window.
Python 3.2.2 (default, Sep 5 2011, 21:17:14)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
The opening message shows the Python version, some build information, and four commands that may be used to get more information about python. license() provides a brief history of python including release years of major version and detailed information about the python distribution and license agreement. credits() provides a brief message of thanks to organizations and individuals who have supported python. copyright() provides a short list of copyrights that pertain to the Python. help() will execute the python help subsystem, which offers detailed information about python functions primarily derived from help strings.
The Python help() command will be discussed in detail later in this tutorial in a separate section.
Python's default prompt command prompt is >>>. Python displays a cursor to the right of the >>> prompt and python commands should be entered there.
To exit the shell and return to the system prompt, type exit() or Ctrl-D.
The shell itself does not offer much functionality to the user other than to provide a command line for entering python commands and functions. Editing capabilities in the shell are extremely limited.
Commands entered into the shell may be recalled by scrolling backward and forward through the command history using the up arrow and down arrow key. The left and right arrow keys are useful to reposition the cursor while editing the current line. The backspace key is destructive and will delete the character to the left of the cursor. It is possible to toggle between insert and overwrite modes by pressing the insert key. The delete key works like the backspace key except that it deletes the character at the cursor rather than the character to the left of the cursor. The home key repositions the cursor to the leftmost character on the current line while the end key repositions the cursor to the end of the line. Pressing enter will attempt to execute the current line no matter where the cursor is positioned. Note that pressing enter will not break the current at the cursor.
The shell maintains a partial history of commands that have been entered starting each time the shell is invoked. The history is not preserved between sessions.
The PageUp selects the first command in the history list for editing while the PageDown key performs the complementary function editing the last command entered.
Most python users will have little use for the command shell interpreter. Probably it's most common use is as a calculator. Arithmetic expressions entered at the command line will be evaluated immediately and the result displayed. The result of the most recent calculation is assigned to the underscore character. The following shows the use of the underscore character.
Basic Arithmetic with PythonEdit
Python has two basic numeric types: int (integer) and float (floating point). A python integer can be of any length. Python integers do not have a minimum or maximum (lower or upper) limit although naturally processing speed is reduced when dealing with very long integers. At the command line, Python will recognize that a number is an int if it is entered with no decimal point and that it is a float if a decimal point is included. Python will recognize that 1 is an int while 1.0 is a float. A real can be cast to an int and vice versa like this: float(1) casts an integer to a float, while int(1.1) casts an int to a float.
Python 3.2.2 for 32-bit Windows provides the following information regarding the numeric floating point type:
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 offers the following well known and understood symbols for arithmetic operations.
Modulus %; Multiplication *; Division / (equal precedence)
Addition +; Subtraction - (equal precedence)
Python observes typical precedence for these operators in the order shown. Calculations enclosed between parentheses have the highest precedence. When precedence of operations is not dictated by operator precedence or grouping by parentheses, calculations are performed from left to right.
1. Start the python interpreter. Note the version number that is displayed on the welcome screen. Exit the shell. Restart the shell. Try entering the different commands that are listed in the welcome message (help, copyright, credits, license). Try some calculations. Try dividing two integers that you would expect would produce an fractional result (for example, 5/2). Note the result. Try various combinations of operations to convince yourself that the order of precedence is predictable. Be sure to experiment with parentheses. Enter 2*(5+ at the command line. What happens when you don't match each left parenthesis with a right parenthesis?
2. Consider other ways to start the python command line interpreter. Consider which method you favor and why.
Python scripts may be created in any text editor with a couple of caveats. 1. It is generally advisiable to include a shebang line when writing for Unix types of systems. 2. In some Unix type environments, the interpreter may have problems with DOS type line endings.
A full installation of Python includes an IDE called IDLE. The name IDLE looks as if it is an acronym for something but like Python itself, it is a name borrowed from Monty Python, in this case the last name of Monty Python regular Eric Idle. IDLE was written by Python progenitor's, Guido von Rossum.
IDLE is included with most or all versions of Python available from the official python website, Python.org. It is often not included with other alternate versions of Python, such as IronPython and ActivePython.
You can start IDLE from the shell or command window, however the preferred method would be to start IDLE via your OS's GUI menu. By default, IDLE open's two Windows: the editor and the shell.
The IDLE shell resembles the command interpreter shell but provides significant additional functionality. Before discussing the additional functionality, note that we lost one of the handier features of the command interpreter shell, the capaibility to scroll and forwards through history list of commands with the up and down arrows keys. In the IDLE shell, if you want to edit re-execute a previously issued command you can use Alt-p and Alt-n to scroll through the recent command list. You can also find the previously issued command in the window, position the cursor on it, and press the enter key. Unlike the command shell interpreter, IDLE keeps a history of all commands in the shell from the beginning of the session until the shell is closed.
Both IDLE shell and the IDLE editor support the mouse and scroll bars for navigating and editing content in their Windows.
The following is quoted verbatims from the 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 http://www.python.org/idle/ There is a mail list for IDLE: email@example.com. You can join at http://mail.python.org/mailman/listinfo/idle-dev
This may prove sufficient introduction for many users. The IDLE help menu offers addition instruction information regarding uses and features of IDLE's menus and options and the entire contents of the help are reproduced here.
[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
Rather than try to elaborate on or reword the lucid explanations provided in the IDLE documentation, what follows is just a series of exercises that are designed to familiarize the reader with menu items and features of the IDLE IDE.
1. Find and open IDLE from your OS's GUI menu. Try closing the editor. Note that closing the editor does not terminate the shell. Use the File|New Window menu item from the shell to open a new Editor window. Using the same menu item, determine whether you can have more than editor window open at a time.
2. Now close the shell. Reopen the shell by using the IDLE editor's Windows|*Python Shell* menu item.
3. Enter a short program in the shell, something like
for n in range(0,10): print(n)
Be sure to press enter after the colon at the end of the first line. Notice that IDLE indents automatically. What do you think triggers the identation?
4. Re-enter the line with deliberate mistakes. What happens?
5. Locate a valid copy of the code in the shell window. Using the mouse or arrows position the cursor (the thin blinking vertical bar) to the line reading for n in range(0,10): and press enter. Notice that the entire block of code is copied to the active prompt where you can edit it. Try copying the same code by selecting it with mouse and pressing Ctrl-C to copy and then paste at the current position. Consider which method is easier for you to use.
6. Copy the same code and paste in into the editor window. Check the script with the IDLE editor's Run|Check Module menu item. Try to run the script with the IDLE Editor's Run|Run Module menu item or with the F5 key. You should have found that in order to do either you need to save the script. There is a way to direct the IDLE editor to save script changes automatically. Where do you suppose that option is found? Be advised that IDLE does not create backup copies of your scripts but that it does keeps 1000 undo steps in memory. Consider methods that you might use to keep an external audit trail so that you revert to an earlier version of your code if necessary.
7. Save the code in the text editor if you have not already. Note whether you need to type the .py extension or whether the save dialog automatically does it for you.
8. Save the contents of the shell window. Open the saved contents in the IDLE editor. Can you think of any situation where saving the contents of the shell window might be useful?
9. Tear off a copy of any drop down menu by clicking on the dashed lined at the top of the menu. Close the floating copy of the drop down menu. Consider whether this is a useful feature and what you might use it for.
10. Compare the main menu items shown in the shell with those in the editor. Notice that each has seven menus but that the editor has a Format item where the shell has a Shell item.
11. Try out the various options from the IDLE editor's Format menu. You may cut and past the following snippet into your IDLE editor for practice:
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)