1.15. Summary

Section references in square brackets indicate where an idea was first discussed.

Where Python syntax is illustrated, the typeface continues to indicate the category of each part:

Typeface Meaning
Typewriter font Text to be written verbatim
Emphasized A place where you can use an arbitrary expression.
Bold A place where you can use an arbitrary identifier.
Normal text A description of what goes in that position, without giving explicit syntax

If there are several variations on a particular part of the syntax, alternatives will be show on successive lines.

To emphasize the successive parts of the syntax, space will generally be left around symbol and punctuation characters, but the space is not required in actual use.

  1. Python Shell

    1. A Shell window may be opened in Idle Run ‣ Python Shell [Windows in Idle]
    2. Entering commands:
      1. Commands may be entered at the >>> prompt. [Addition and Subtraction]
      2. If the Shell detects that a command is not finished at the end of the line, a continuation line is shown with no >>>. [Multiplication, Parentheses, and Precedence]
      3. Statements with a heading ending in a colon followed by an indented block, must be terminated with an empty line. [Basic for Loops]
      4. The Shell evaluates a completed command immediately, displaying any result other than None, starting on the next line. [Addition and Subtraction]
      5. The Shell remembers variable and function names. [Variables and Assignment]
    3. An earlier Shell line may to copied and edited by clicking anywhere in the previously displayed line and then pressing Enter.
  2. Idle editing

    1. Start a new window from the File menu by selecting New, Open..., or Recent Files. [Loading a Program in the Idle Editor, and Running It]
    2. Make your Python file names end with ‘.py’ [Literals and Identifiers]
  3. To run a program from an Idle Editor Window:

    1. Select Run -> Run Module or press function key F5. The program runs in the Shell window, after resetting the shell so all old names are forgotten. [Loading a Program in the Idle Editor, and Running It]
      1. If the program is expecting keyboard input, the text cursor should appear at the end of the Shell history. If you somehow move the cursor elsewhere, you must explicitly move it back. [The Idle Editor and Execution]
      2. Press Ctrl-C to stop a running program in a long or infinite loop.
      3. After a program terminates, the Shell remembers function definitions and variable names define outside of any function. [A First Function Definition]
  4. Errors come in three categories:

    1. Syntax errors: text that the interpreter recognizes as illegal when first reading it. This prevents execution of your code. Python lets you know where it realized there was an error. Sometimes this is the exact location, but the actual error could be anywhere earlier, often on the previous line. [Variables and Assignment]
    2. Execution errors: The first illegal action is detected while running your command or program. The source of the error could be in the line where execution fails, or it could be an earlier logical error that only later forces an execution error. [Variables and Assignment] Execution errors generate a traceback. [Function Parameters]
    3. Logical errors: When Python detects nothing illegal, but you do not get the results you desire. These errors are the hardest to trace down. Playing computer and additional print functions help. [More Playing Computer]
  5. Type int, (short for integer):

    1. Literal integer values may not contain a decimal point. [Floats, Division, Mixed Types]
    2. Integers may be arbitrarily large and are stored exactly. [Floats, Division, Mixed Types]
    3. Integers have normal operations, with usual precedence (highest listed first):
      1. **: exponentiation (5**3 means 5*5*5) [Exponentiation, Square Roots]
      2. *, /, //, %: multiplication, division with float result, integer division (ignoring any remainder), just the remainder from division [Division and Remainders]
      3. +, -: addition, subtraction [Addition and Subtraction]
  6. Type float, (short for floating point): approximations of real numbers

    1. Literal values must contain a decimal point to distinguish them from the int type [Floats, Division, Mixed Types]
    2. Approximates a wide range of values [Floats, Division, Mixed Types]
    3. Does not dependably store numbers exactly - even numbers with simple decimal representation [Floats, Division, Mixed Types]
    4. Has the same operation symbols as for integers, but always with a float result [Floats, Division, Mixed Types]
    5. A mixed binary operation with an integer and a float produces a float result. [Floats, Division, Mixed Types]
  7. Type str, (short for string): Literal values contain a sequence of characters enclosed in matching quotes.

    1. Enclosed in ' or ": The string must be on one line. [String Delimiters, Part I]

    2. Enclosed in ''' or """: The string may include multiple lines in the source file. [Triple Quoted String Literals]

    3. Escape codes inside literals include \' for a single quote and \n for a newline. [Escape Codes]

    4. Binary operations (operation symbols have the same precedence order as when the symbols are used in arithmetic) [String Concatenation]

      1. stringExpression1 + stringExpression2

        concatenation (running together) of the two strings

      2. stringExpression * integerExpression
        integerExpression * stringExpression

        Repeat the string the number of times given by the integer expression.

    5. string format method:

      1. stringFormatExpression .format( parameter0 , parameter1 , parameter2 , ... )

        [String Format Operation] where stringFormatExpression is any string with an arbitrary number of places for format substitutions in it. Formatted substitutions are enclosed in braces. A digit inside the braces will indicate which parameter value is substituted, counting from 0. If digits are left out, the format parameters are substituted in order. The expression inside the braces can end with a colon : followed by a format specifying string such as .#f where # can be a non negative integer: substitute a numerical value rounded to the specified number of places beyond the decimal point. [Floats, Division, Mixed Types]


        'word: {}, int: {}, formatted float: {:.3f}.'.format('Joe', 23, 2.1357)

        evaluates to:

        'word: Joe, int: 23, formatted float: 2.136.'
      2. stringFormatExpression .format( ** dictionary )

        The format expressions are the same as above except that a key name from a dictionary appears inside the braces. The dictionary referenced appears in the parameter list preceded by **. Any value to be substituted is then taken from the dictionary by accessing the key. Example: If defs is a dictionary with defs['name'] equaling 'Joe', defs['num'] equaling 23, defs['dec'] equaling 2.13579, then

        'word: {name}, int: {num}, formatted float: {dec:.3f}.'.format(**defs}

        evaluates to the same string as in the previous example. [Dictionaries and String Formatting]

        In particular, the dictionary reference can the the dictionary of all local variable names, by making the parameter to format be **locals(). [Dictionaries and Python Variables]

    6. Strings are a kind of sequence.

  8. Type list

    [ expression1 , expression2 , and so on ]
    [ expression ]
    1. A literal list consists of a comma separated collection of values all enclosed in square brackets. There may be many, one, or no elements in the list. [The list Type]
    2. A list is a kind of sequence, so it may be used as the sequence in a for statement heading. [Basic for Loops]
  9. Type dict (short for dictionary)


    returns an empty dictionary

    1. A dictionary provides an association of each key to its value. The key can be any immutable type, with includes numbers and strings. [Definition and Use of Dictionaries]

    2. dictName [ keyExpression ] = valueExpression

      associates in the dictionary dictName the key derived from evaluating keyExpression with the value derived from evaluating valueExpression. [Definition and Use of Dictionaries

    3. Used in an expression,

      dictName [ keyExpression ]

      evaluates to the value in the dictionary dictName coming from the key obtained by evaluating keyExpression. [Definition and Use of Dictionaries]

  10. Type of None: This literal value has its own special type. None indicates the absence of a regular object.

  11. Identifiers

    1. Identifiers are names for Python objects [Literals and Identifiers]
    2. They may only contain letters, digits, and the underscore, and cannot start with a digit. They are case sensitive. [Literals and Identifiers]
    3. You cannot use a reserved word as an identifier, nor are you recommended to redefine an identifier predefined by Python. In the Idle editor you are safe if your identifier names remain colored black. [Literals and Identifiers]
    4. By convention, multi-word identifiers either [Literals and Identifiers]
      1. use underscores in place of blanks (since blanks are illegal is identifiers), as in initial_account_balance
      2. use camel-case: all lowercase except for the starting letter of the second and later words, as in initialAccountBalance
  12. Variables are identifiers used to name Python data [Variables and Assignment]

    When a variable is used in an expression, its latest value is substituted. [Variables and Assignment]

  13. Statements

    1. Assignment statement: [Variables and Assignment]

      variable = expression

      1. The expression on the right is evaluated, using the latest values of all variables, and calculating all operations or functions specified.
      2. The expression value is associated with the variable named on the left, removing any earlier association with the name.
    2. For-statement

      for item in sequence :
      consistently indented statement block, which may use the variable item

      For each element in the sequence, repeat the statement block substituting the next element in the sequence for the variable name item. See Programming Patterns for patterns of use. [Basic for Loops]

    3. Return statement

      return expression

      This is used only in a function definition, causing the function to immediately terminate and return the value of expression to the calling code, effectively acting as if the function call was replaced by this returned value. [Returned Function Values]

  14. Function calls

    functionName ( expression , expression , and so on )

    1. The number of expressions must correspond to a number of parameters allowed by the function’s definition. [Function Parameters]
    2. Even if there are no parameters, the parentheses must be included to distinguish the name of the function from a request to call the function. [A First Function Definition]
    3. Each expression is called an actual parameter. Each actual parameter is evaluated and the values are passed to the code for the function, which executes its defined steps and may return a value. If the function call was a part of a larger expression, the returned value is used to evaluate the larger expression in the place where the function call was. [Function Parameters]
    4. If nothing is returned explicitly, the function returns None.
    5. Function calls may also be used as statements, in which case any value that is returned is ignored (except if entered directly into the shell, which prints any returned value other than None).
    6. Keyword arguments are a special case. They have been used optionally at the end of the parameter list for print.
  15. Functions that are built-in

    1. Print function: [Print Function, Part I] [The print function keyword end]

      print( expression )
      print( expression , expression , expression )
      print( expression , expression , ``sep=strVal, end=strVal )
      1. Print the value of each expression in the list to the standard place for output (usually the screen) separating each value by individual blanks unless the keyword argument sep is specified to change it. There can be any number of expressions (not just 1-3 as illustrated).
      2. The string printed ends with a newline unless the keyword argument end is specified to change it.
      3. With no expression, the statement only advances to a new line.
    2. A type name can be used as function to do obvious conversions to the type, as in int('234'), float(123), str(123). [Numbers and Strings of Digits]

    3. type( expression )

      Return the type of the value of the expression. [String Delimiters, Part I]

    4. input( promptString )

      Print the promptString to the screen; wait for the user to enter a line from the keyboard, ending with Enter. Return the character sequence as a string [The input Function]

    5. len( sequence )

      Return the number of elements in the sequence [Whirlwind Introduction To Types and Functions]

    6. range( expression )

      Require expression to have a non negative integer value, call it n. Generate a sequence with length n, consisting of the numbers 0 through n-1. For example range(4) generates the sequence 0, 1, 2, 3 [The range Function, Part 1]

    7. max( expression , expression , and so on )

      Return the maximum of all the expressions listed. [Whirlwind Introduction To Types and Functions]

    8. format( expression , formatString )

      If expression is numeric, the format string can be in the form '.#f', where the # gets replaced by a nonnegative integer, and the result is a string with the value of the expression rounded to the specified number of digits beyond the decimal point. [Floats, Division, Mixed Types]

  16. Functions defined by a user:

    def functionName ( parameter1 , parameter2 , and so on ) :
    consistently indented statement block, which may include a return statement
    1. There may be any number of parameters. The parentheses must be included even if there are no parameters. [Function Parameters]
    2. When a function is first defined, it is only remembered: its lines are not executed. [A First Function Definition]
    3. When the function is later called in other code, the actual parameters in the function call are used to initialize the local variables parameter1, parameter2, and so on in the same order as the actual parameters. [Function Parameters]
    4. The local variables of a function are independent of the local names of any function defined outside of this function. The local variables must be initialized before use, and the names lose any association with their values when the function execution terminates. [Local Scope]
    5. If a return statement is reached, any further statements in the function are ignored. [Returned Function Values]
    6. Functions should be used to:
      1. Emphasize that the code corresponds to one idea and give an easily recognizable name. [A First Function Definition]
      2. Avoid repetition. If a basic idea is repeated with just the data changing, it will be easier to follow and use if it is coded once as a function with parameters, that gets called with the appropriate actual parameters when needed. [Function Parameters]
      3. It is good to separate the internal processing of data from the input and output of data. This typically means placing the processing of data and the return of the result in a function. [Function Parameters]
      4. Separate responsibilities: The consumer of a function only needs to know the name, parameter usage, and meaning of any returned value. Only the writer of a function needs to know the implementation of a function. [Two Roles: Writer and Consumer of Functions]
  17. Modules (program files)

    1. A module may start with a documentation string. [Program Documentation String]
    2. Define your functions in your module. If the module is intended as a main program called only one way, a convention is make your execution just be calling a function called main. [Multiple Function Definitions]
    3. Avoid defining variable outside of your functions. Names for constant (unchanging) values are a reasonable exception. [Global Constants]
  18. Documentation String: A string, often a multi-line (triple quoted) string that may appear in two places:

    1. At the very beginning of a file: This should give overall introductory information about the file [Program Documentation String]
    2. As the very first entry in the body of a function: This should describe: [Definition and Use of Dictionaries]
      1. The return value of the function (if there is one)
      2. Anything about the parameters that is not totally obvious from the names
      3. Anything about the results from the function that is not obvious from the name
  19. Programming Patterns

    1. Input-calculate-Output: This is the simplest overall program model. First obtain all the data you need (for instance by prompting the user for keyboard input). Calculate what you need from this data. Output the data (for instance to the screen with print functions). [The input Function]

    2. Repetitive patterns: These patterns are all associated with loops. Loops are essential if the number of repetitions depends on dynamic data in the program. Even if you could avoid a loop by repeating code, a loop is usually a better choice to make the repetitive logic of your program clear to all.

      1. Exact repetition some number of times: If the number of time to repeat is n:

        for _ in range( n ):
        actions to be repeated

        Here the variable _ is included only because there must be a variable name in a for loop. [Simple Repeat Loop]

      2. For-each loop: Do the same sort of thing for each item in a specified sequence. [Basic for Loops]

        for item in sequence :
        actions to be done with each item

        The sequence can be a range, where item is the next integer in the range.

      3. Successive modification loop: Repeat a basic idea, but where the data involved each time changes via a pattern that is coded in the loop to convert the previous data into the data needed the next time through the loop [Successive Modification Loops]:

        initialize all variables that will be successively modified in the loop
        loop heading for the repetition :
        actions to be in each loop with the current variable values
        modify the variable values to prepare for the next time through the loop
      4. Accumulation loop: A sequence of items need to be combined. This works where the accumulation of all the items can be approached incrementally, combining one after another with the accumulation so far [Accumulation Loops]:

        initialize the accumulation to include none of the sequence
        for item in sequence :
        new value of accumulation = partial result

        where the partial result comes from combining item with the current value of accumulation

  20. Playing computer: following code line by line of execution. This either tests that you understand your code (and it works right) or it helps you find where it goes wrong. [Updating Variables, Successive Modification Loops, More Playing Computer]

    1. Make sure line numbers are labeled
    2. Make a table with heading for line numbers, all variables that might be changing, and comments
    3. Follow the order of execution, one statement at a time, being careful to update variable values and only use the latest variable values, and carefully following the flow of control through loops and into and out of function calls. With loops and user function calls, the order is not just textual sequential order!