OUTDATED, DO NOT USE: This tutorial was written in 1999 and was based on Python 1.5.2, which today is a really old version. I would not recommend using this tutorial to learn modern Python as the language has changed significantly. This page is left here in it's mostly-original form for historic reference only. Please consult the Python website for current documentation.

File structure

  • Comments start with '#' and continue to end of line
  • Lines may be continued by putting '\' at end of line
  • Blocks are indicated by indentation level only; no Begin/End or {} blocks
    if year >= 2001:
       print 'Welcome to the 21st millenium'
    else:
       print 'Not there yet'
    
  • Source files (modules) usually named with ".py" extension. Python automatically produces bytecode compiled versions with ".pyc" extension.
  • To run python interactively, enter
    $ python
    
    or to run a python script
    $ python myscript.py
    
  • To make python scripts directly executable under Unix, usually write
    #!/usr/bin/env python
    
    def myfunction():
       ...
    
    # equivalent to C's main() entry point function
    if __name__ == '__main__':
       myfunction()
    
    Be sure to set Unix execute permission bit with: chmod +x filename.py

Names and keywords

  • All names (keywords, variables, etc.) are case sensitive.
  • Names follow C syntax. They must start with a letter or underscore and may be follows by any number of of letters, digits, and underscores.
  • Names starting with two underscores are reserved for internal Python use.
  • Names starting with just a single underscore may be defined by the user, and usually indicate private variables.
  • Names (variables, etc.) are automatically defined when you first use first assign a value to them. However a name must already exist before it can be referenced.
  • Most builtin functions in Python are not reserved. A user may replace them with their own definition if desired. However there are a few keywords which are reserved. They can not be used as variable names or redefined.
    and
    assert
    break
    class
    continue
    def
    del
    elif
    else
    except
    exec
    finally
    for
    from
    global
    if
    import
    in
    is
    lambda
    not
    or
    pass
    print
    raise
    return
    try
    while
  • Furthermore you may wish to avoid the use of the following words as variable names (at least until you understand Python better), even though they are not reserved.
    None
    apply
    compile
    complex
    dir
    eval
    float
    hash
    hex
    id
    int
    len
    list
    long
    map
    max
    min
    open
    reload
    repr
    round
    slice
    tuple
    type

Basic types

  • Python has no specific Boolean type. Instead it uses the C convention of using 0 for false and anything else for true.
  • Whenever boolean values are created, such as with comparison functions, true is always 1.
    print 5 < 8    --> 1
    
  • If the type is non-numeric, it is considered to be false if it is empty or of zero length, and true if it contains anything.
    if "hi": print 'true'     --> true
    if "": print 'true'       -->
    
  • A special predefined value named None is used to indicate the condition of "no value". It is always considered to be false. Note that None is different than an empty value, like a zero-length string. It is in some respects similar to the C NULL pointer, only Python does not deal with pointers.
  • Everything in python has a type of some sort, even functions. In general you can print them out and something reasonable should be displayed.
    print 45              --> 45
    print "hello"         --> "hello"
    print lotterynumbers  --> [14,21,25,37,40]
    print printbill       --> function printbill at 873045
    
  • In fact, any value which is returned is displayed. Also, constants always return themselves. This allows Python to have perhaps the shortest "Hello World" program of any language:
    "Hello World"    --> "Hello World"
    
    Or it makes Python an excelent interactive calculator,
    1+2             --> 3
    (4 * 5.3) / 14  --> 1.51428571429
    

Numbers

  • Python supports integer, long (infinite size), floating-point, and complex numbers
  • Integers (really C "long" type) use C-style conventions:
    15    # decimal number
    0x4E  # hexadecimal number
    0177  # octal number
    
  • Long integers support infinite number of digits (put "L" after last digit),
    12345678901234567890123456789L
    
  • Floating-point numbers use C conventions (really a C "double" type)
    3.1415
    4.2e-6  using exponential form
    
  • Complex numbers are written using the engineering "J" notation,
    3+4j
    2.1+0.45j
    
  • All numbers are signed, there are no C-like "unsigned" types.

Strings

  • Strings are sequences of characters. There is no separate chartacter type, just use strings of length one.
  • Strings are 8-bit clean; doesn't use C's convention of null termination character
  • There are four ways to quote string literals:
    1. Using ' quote, e.g.,   'A string literal'
    2. Using " quote, e.g.,   "A string literal"
    3. Using """ quote for multi-line strings, e.g.,
      """A string which contains
      more than one line"""
      
      Line breaks are maintained in the string as newline characters.
    4. Raw strings don't process \ escapes, mainly used with regular expressions
      r"a raw string"
      
  • Except for raw strings, special characters can be included by using C-style backslash escape codes, e.g,
    "A tab\tcharacter and a\nnewline"
    
    Some of the common escape characters include
      \n Newline (linefeed)
    \t horizontal tab
    \\ a single backslash
    \" a double-quote
    \' a single-quote (apostrophe)
    \e an ASCII escape character
  • Adjacent string literals are concatenated, just like in C
    "This is really"  " just one string"
    
  • If you want to concatenate string variables, you must use the + operator,
    string1 = "hello"
    string2 = "world"
    s = string1 + string2
    print s    --> "helloworld"
    

Basic expressions

  • Most math/logical operators are similar to C, except:
    1. use "or" instead of "||"
    2. use "and" instead of "&&"
    3. use "not" instead of "!" (although != still works)
  • The "**" operator performs exponentiation, e.g., 3**5 is 30,000.
  • There is no C-like ?: operator
  • There are no C-like auto increment/decrement operators (e.g., x++)
  • Assignments can not be part of an expression (e.g., 15 + (n=f(x)))
  • Parentheses can be used to control the order of evaluation
  • Comparisons can be chained such as: 4 < x < 9

String formatting

  • The *-operator will replicate a string
    print "dog" * 3   --> "dogdogdog"
    print "-" * 10    --> "----------"
    
  • To get the effect of C's printf-style formatting, use the % operator. Examples include,
    print "you are %d years old" % 21  --> "you are 21 years old"
    print "I like %s pie" % "apple"    --> "I like apple pie"
    
  • Other formatting %-codes include
      %s include a string
      %d a decimal integer
      %x a hexadecimal number
      %f floating point, like "3.141000"
      %g floating point, like "3.141"
      %e floating point, like "7.62300e+003"
  • To include more than one item use
    print "%d times %d is %d" % (4, 8, 32)  --> "4 times 8 is 32"
    
  • printf-style modifiers may also be used
    print "A%7sZ" % "ghi"   --> "A    ghiZ"
    print "A%-7sZ" % "ghi"  --> "Aghi    Z"
    print "%06d" % 183      --> "000183"
    print "%8.3f" % 1.2     --> "1.200"