Python Cheat Sheet

Python is a dynamic object-oriented programming language with extensive standard libraries. These notes summarize the Python 3.1 tutorial.

  • python/python3.1 is the command-line interpreter with readline where available.
  • python -c command runs a single command.
  • >>> prompts for a line . ... prompts for a continuation of a previous line.
  • PYTHONSTARTUP can point to a file of startup commands
  • Expressions are evaluated and printed.
  • The last printed expression is assigned to _ .

Basics

  • Comments start with # .
  • sys.argv is a list of strings with the script if any in sys.argv[0]
  • Variables can be assigned (using = ) without being defined but must be assigned before being used.
  • a,b = c,d does a multiple assignment.
  • Imaginary numbers can be created using complex(a,b) or a+bJ. .real and .imag will extract real and imaginary parts.
  • print(“a”,“b”,end=“”) prints a b with no newline at the end.

Functions

  • To define a function or procedure
    define func(n,str="default"):
    define func(formal1, formal2, *arguments **keywords)
  • The default value for an argument is evaluated only once when the function is defined.
  • All arguments are passed using call by object reference. So changes are seen by caller.
  • * unpacks a list or dictionary for use in a function.
  • lambda x: x + n creates a small anonymous function.
  • A function should contain a triply quoted doc string at the start. This is accessible with func.doc .
  • 4 spaces per indent, no tabs. CamelCase for classes lower_case with underscores for functions.

Lists

  • list=[1 ,'a' , “b”] is a list of three items.
  • list[4] is 4th element. list[2:4] is second and third elements. list[:2] is first 2 elements. list[2:] is third element to last one. list[:] is the whole list.
  • Negative indexes count from last element.
  • List slices can be modified. list[3:3] can be used to insert elements at position 3.
  • len(list) returns length of the list.
  • Lists can be nested.
  • Other methods include append, pop, extend, index, count, sort, reverse.
  • Lists can be created from sequences using list comprehension
    vec = [2, 4, 6]
    [[x, x**2] for x in vec if x > 2]
    [[4, 16], [6, 36]]
    [x+y for x in vec for y in vec2 if x > 2]
  • Other sequence types include tuples ( (1,2) or 1,2) and sets ({1,2} or set(1,2)).

Input/Output

  • Strings can be enclosed with double or single-quotes.
  • \ in a string by itself goes to the next line but does not insert a newline (\n does).
  • A raw string - r“” does no escaping.
  • + concatenates strings, * repeats them .
  • A string can be treated as a list of letters.
  • But strings can't be modified using slices or indexes.
  • String methods include strip, format, capitalize etc.
  • formatstring.format(tuple) is the new-style printf equivalent. The old-style was formatstring % (tuple) which uses C-type format strings.
  • str() returns a readable representation, repr() returns a canonical representation of any object.
  • To open a file
     open('/tmp/workfile', 'w') 
  • File methods include read, readline, write.
  • pickle contains load and dump methods for serializing objects. Support should be added for new object types.

Control Flow

  • Controlled by level of indentation.
  • pass is a NOOP .
  • while a<10:
      pass
  • for x in list:
      pass
    for x in range(1,5):
      pass
  • if a›10:
       pass
    elif a›5:
       pass
    else:
  • break and continue can be used
  • Loops may have else clauses for code executed after normal termination (not a break).

Assorted Collection Stuff

  • Dictionaries are unordered sets of key value pairs e.g. { a:1, b:2} or dict([(a,1),(b,2)]) or dict(a=1,b=2)
  • Dictionary keys/values/items can be enumerated over.
  • sorted and reversed take in lists and return new lists.
  • enumerate takes in a list and returns a list of pairs where the first item in the pair is an integer starting with 0.
  • zip takes two or more lists with the same number of elements and creates a single list of lists with corresponding members grouped together.

Modules & Packages

  • A module is a file of python definitions.
  • Definitions in a module can be accessed by importing the module.
    import fib
    from fib import fib1, fib2
  • __name__ is set to the name of the module or to __main__ if called from the command line.
  • The search list for modules is the variable sys.path initialized from the directory containing the input script (or the current directory), PYTHONPATH and the installation-dependent default.
  • When a module is imported, a byte-code version is stored to module.pyc which speeds up successive loads.
  • There are many standard modules including sys which is common to all platforms.
  • dir(module) lists all names in a module sorted alphabetically. dir(builtins) shows all the built-in functions and variables.
  • Packages can be used to group modules. Packages should be in a named directory with an init.py file optionally containing initialization code. E.g. import sound.effects.echo .
  • . is the current package, .. is the parent package etc.

Error Handling

  • Syntax errors are parsing errors, exceptions are runtime errors.
  • Exceptions are class objects in the exceptions module. List of builtin exceptions.
  • Exception handling is supported using try..except..else..finally :
    try:
        result = x / y
    except ZeroDivisionError:
        print("division by zero!")
    except Exception as inst:
        print(type(inst))    # the exception instance
        print(inst.args)     # arguments stored in .args
        print(inst)          # also prints .args
    else:
        print("result is", result)
    finally:
        print("executing finally clause")
  • Errors can be raised using raise Exception('mine') or just raise in an exception handler.
  • New exception classes can be created and should derive from the Exception class.
  • with can be used to automatically call the cleanup actions of an object e.g.
    with open("myfile.txt") as f:
        for line in f:
            print(line)

Classes

Recent changes RSS feed Creative Commons License Donate Minima Template by Wikidesign Driven by DokuWiki