../_images/python.png

2.1. Introduction to Python

2.1.1. Python Features

  • Interpreted: platform independent, very high level, rapid development cycle

  • Very clear syntax: easy to learn, even just by example

  • Fully Object Oriented, but not mandated

  • No need to initialize variables

    Python determines data type of variables by how they are used.

    • A number expressed as and integer is an int (i = 5).
    • A number with a decimal point is a float (x = 3.5).
    • Character data is put in quotes and is a str (string) (st = ‘Hello, World’).
  • Advanced built-in data structures allows for rapid development.

2.1.2. Indentation and block-structure

  • Use colon and indention to identify a code block.

  • No need for semicolons or brackets:

    n = 9
    r = 1
    while n > 0:
        r = r * n
        n = n – 1
    print r

2.1.3. Strings

  • Initialize strings with pairs of single quotes, double quotes, or triple quotes:

    a = '\t this starts with a "tab".'
    b = "this string has 'line feed'.\n"
    c = "backslash \"quotes\"."
    d = 'same for \'single\' quotes.'
    
    e = """The triple quote is nice for strings that take multiple
    lines. 'single' and "double" quotes do not need backslashes."""
    
  • Merging variables with strings:

    st = "There are %d lines and %d characters in the file" % (chars, lines)
    

2.1.4. Introducing Lists

  • Very flexible built-in data container
  • Like an array, a list contains a sequence of data items
  • A list can contain a mixture of data types including any number type, strings, tuples, lists, dictionaries, functions, objects of any type
  • Mixture of data types allows easy creation of data structures

2.1.5. Introducing Tuples

  • A tuple is a list that is immutable (can not be changed once created)

    x = (1, 2, 3)

  • Use tuples when possible because they are more efficient than lists

  • Operators and built-in functions (in, +, *, len(), min(), max()) may be used with tuples

  • Tuples are used to facilitate saving multiple values returned from a function

>>> def swap(a, b):
...     return(b, a)
...
>>> x = 1
>>> y = 2
>>> x, y = swap(x, y)
>>> x
2
>>> y
1

See also

Tuples

2.1.6. Introducing Dictionaries