Introduction to Python

Python is a simple but powerful scripting language. It was developed by Guido van Rossum in the Netherlands in the late 1980s. The language takes its name from the British comedy series Monty Python's Flying Circus. Python is an interpreted language unlike C or Fortran that are compiled languages.

Monty Python and the Fish Slapping Dance

Monty Python and the Cheese Shop

Monty Python and the Dead Parrot

Why Python?

This means that you can be productive quite easily and fast. You will be spending more time solving problems and writing code than grappling with the idiosyncrasies of the language.

Your First Program

You can use Python interactively. When you start Python in the interactive mode you will see the following prompt >>>. Your first interaction and response will be as follows:

>>> print "Hello World!"
Hello World!

For longer programs you can store your program in a file that ends with a .py extension. Save your first program in a file called Hello.py. It will have a single statement - print "Hello World!" . To run your program, type at the command line

> python Hello.py

You can also create a stand alone script. On a Unix / Linux machine you can create a script called Hello.py. This script will contain the following lines of code:

#!/usr/bin/python
print "Hello World!"

Before you run it, you must make it into an executable file.

> chmod +x Hello.py

To run the script, you simply call it by name like so:

> ./Hello.py

Structure of a Computer Language

Basic Syntax of Python

Character Set in Python

Python uses the traditional ASCII character set. The latest version (2.7) also recognizes the Unicode character set. The ASCII character set is a subset of the Unicode character set.

Identifiers

Python is case sensitive. These are rules for creating an indentifier:

Variables

A variable in Python denotes a memory location. In that memory location is the address of where the actual value is stored in memory. Consider this assignment:

 
x = 1 

A memory location is set aside for the variable x. The value 1 is stored in another place in memory. The address of the location where 1 is stored is placed in the memory location denoted by x. Later you can assign another value to x like so:

 
x = 2 

In this case, the value 2 is stored in another memory location and its address is placed in the memory location denoted by x. The memory occupied by the value 1 is reclaimed by the garbage collector.

Unlike other languages like Java that is strongly typed you may assign a different type to value to x like a floating point number. There are no types in Python.

x = 3.45

In this case, the value of 3.45 is stored in memory and the address of that value is stored in the memory location denoted by x.

Operators

Arithmetic Operators: These are the arithmetic operators that operate on numbers (integers or floats). The result of applying an arithmetic operator is a number.

Comparison Operators: There are 6 comparison operators. The result of applying the comparison operators is a Boolean - True or False.

You may apply the comparison operator between two operands like so (a > b). You can also apply the comparison operators in sequence like so (a > b > c). However, this is a practice that is not recommended.

Boolean Operators: In Python, we have two Boolean literals - True and False. But Python will also regard as False - the number zero (0), an empty string (""), or the reserved word None. All other values are interpreted as True. There are 3 Boolean operators:

Assignments

A variable can be assigned to a literal or to an expression.

a = 1                # 1 is an integer literal
b = 2.3              # 2.3 is a floating point literal
c = False            # False is a boolean literal
d = 5L               # 5L is a long integer literal
e = 8 + 6j           # 8 + 6j  is a complex literal
f = "Hello"          # "Hello" is a string literal

An expression is composed of variables and operators. The simplest expression is just a variable. The value of an expression is evaluated before it is used. Python allows for multiple assignments at once. Hence doing a swap in Python is extremely simple:

x, y = y, x

Conditionals

In Python, a conditional allows you to make a decision. You can use the keyword elif that is a contraction of the words else and if.

  if (cond1):
    ...
  elif (cond2):
    ...
  else:
    ...
The body of if, elif, and else parts need to be indented.

Loops

The loop construct in Python allows you to repeat a body of code several times. There are two types of loops - definite loops and indefinite loops. You use a definite loop when you know a priori how many times you will be executing the body of the loop. You use key word for to begin such a loop. You use an indefinite loop when you do not know a priori how many times you will be executing the body of the loop. You use the key word while to begin indefinite loops. To write an efficient loop structure you must ask yourself 3 questions:

While Loop: Syntactically the simplest loop construct is the while loop.

  while (cond):
    ...
    loop_body
    ...

For Loop: A definite loop starts with for and then the sequence or range is given. A definite loop uses a loop counter. By convention, we use i as the loop counter but any variable could be used in its place. Here are several examples of the use of the for loop.

Write a loop that executes the body 10 times.

for i in range (10):
  ...
  loop_body
  ...
The loop counter i goes through the values 0 through 9 as the loop iterates.

We can also specify the beginning and ending value of i. Let us say we wanted i to start at 3 and end at 14. Then the loop could be written as:

for i in range (3, 15):
  ...
  loop_body
  ...
Note that we used 15 instead of 14 as the ending value since the ending value is not inclusive. The loop counter i will take all the values between 3 and 14 both inclusive in the above piece of code.

We can also specify the step size for the loop counter.

for i in range (1, 10, 2):
  ...
  loop_body
  ...
Here i will take all the odd values from 1 to 9 inclusive.

If the step size is not uniform and cannot be expressed by a simple mathematical formula then we can also enumerate all the values that the loop counter i will take. The set of values that i will take is called a sequence.

for i in [7, 4, 18, 12]:
  ...
  loop_body
  ...

Functions

You can think of a function as a small piece of code that has one specific functionality. Functions need to be called. They can be called within main() or within other functions. A function could also call itself, defining what we call recursive functions. Depending on what the function was intended to perform, it may or may not return a value or values.

The structure of a function definition is as follows:

  def function_name ([formal_parameters]):
    ...
    body_of_the_function
    ...
The function_name is an identifier in Python and obeys the same rules for its construction. The formal parameters are optional. You can have zero or more parameters. However, even if you have no formal parameters, you must have the open and close parentheses. You can think of the formal parameters as placeholders that accept values sent to it from the calling function. When a function is called, the parameters that are passed to it are called actual parameters.

Here is a complete list of built-in functions.

There are other functions that reside in modules that have to be loaded before you can use them like string, math, and random. You load these modules by using the import directive.

  import string
  import math, random
After you load the module you can call on the functions using the dot operator.
  x = 7
  y = math.sqrt (x)
  z = random.random()

To call a user defined function that is in the same program you simply call it by name without using the dot operator. If the function does not return a value, then call it on a line by itself. If it returns values then assign those return values to the corresponding variables.

  def addTwo (a, b):
    return a + b

  def divide (a, b):
    return a / b, a % b

  def isEven (x):
    return (x % 2 == 0)

  def gcd (m, n):
    while (m != n):
      if (m > n):
        m = m - n
      else:
        n = n - m
    return m

  def coPrime (a, b):
    if (gcd(a, b) != 1):
      return
    else:
      print "%0d and %0d are co-prime" % (a, b)

  def main():
    x = 2
    y = 3

    z = addTwo (x, y)

    p, q = divide (x, y)

    if (isEven(z)):
      print z
    
    coPrime (x, y)

  main()

Arrays or Lists

The analogue of an array in Python is a list. A list is a collection of heterogenous items that is dynamic. The size of the list is not specified at creation and can grow and shrink as needed. Python provides built-in functions to manipulate a list and its contents. Given the flexibility and the associated functions, a Python list is a more powerful data structure than an array.

There are several ways in which to create a list. You can enumerate all the elements of a list or create an empty list and then append or insert items into the list.

  # Enumerate the items
  a = [1, 2, 3]

  # Create an empty list and append or insert
  a = []
  a.append(1)            #  a = [1]
  a.append(2)            #  a = [1, 2]
  a.insert(1, 3)         #  a = [1, 3, 2]

  # Create a two dimensional list
  b = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]

To obtain the length of a list you can use the len() function.

  a = [1, 2, 3]
  length = len (a)         # length = 3
The items in a list are indexed starting at 0 and ending at index length - 1. You can also slice a list by specifying the starting index and the ending index and Python will return to you a sub-list from the starting index and upto but not including the end index.
  a = [1, 9, 2, 8, 3, 7, 4, 6, 5]
  b = a[2:5]                # b = [2, 8, 3]

One of the most important operations that you can do with a list is to traverse it, i.e. visit each and every element in the list in order. There are several ways in which to do so:

  a = [9, 2, 6, 4, 7]
  for item in a:
    print item,               # 9 2 6 4 7

There are other useful List Functions that can sort or reverse lists.

Tuple

A tuple is like a list. It is an ordered sequence but unlike a list it is immutable. It is created by specifying the items in the tuple within parentheses and separated by commas.

  coord = (7.3, 2.9)
  employee_record = ('john', 'doe', '123 Any Street', 'Austin', 'TX')
Tuples have many uses like specifying the (x, y) coordinates of a point in Cartesian space or employee records from a database. You may not assign to individual elements in a tuple. You can extract individual elements from a tuple by what is known as sequence unpacking.
  x, y = coord
  first, last, street, city, state = employee_record
In general, use a tuple instead of a list when you know that you will not be changing the elements in it. Going from a list to a tuple and vice versa is fairly simple:
  a = [1, 2, 3, 4]
  b = tuple (a)        # b = (1, 2, 3, 4)
  p = ('a', 'b', 'c')
  q = list (p)         # q = ['a', 'b', 'c']

Set

A set is an unordered collection of unique objects. You can create a set from a list. If you do all duplicate elements are eliminated and the ordering is lost.

  a = [1, 1, 2, 2, 2, 3, 4, 4, 4, 4]
  b = set (a)     #  b = set([1, 2, 3, 4])
A set supports the mathematical operations of union, intersection, difference, and symmetric difference.
  # define two sets
  a = set ('abracadabra')    # a = set(['a', 'r', 'b', 'c', 'd'])
  b = set ('alacazam')       # b = set(['a', 'c', 'z', 'm', 'l'])

  # Union of the two sets
  c = a | b                  # c = set(['a', 'c', 'b', 'd', 'm', 'l', 'r', 'z'])

  # Intersection of the two sets
  d = a & b                  # d = set(['a', 'c'])

  # Difference of the two sets (letters in a but not in b)
  g = a - b                  # g = set(['r', 'b', 'd'])

  # Symmetric difference letters in a or b but not both
  h = a ^ b                  # h = set(['b', 'd', 'm', 'l', 'r', 'z'])

  # To get the number of elements in a set
  num_elements = len (a)

  # To iterate over the elements in a set
  for elt in a:
    print elt

  # To convert a set into a list
  p = list (a)

Dictionary

A dictionary is an unordered collection of key-value pairs. The keys are unique and have to be immutable types like numbers or strings. In other languages a dictionary is called an associative array, hash, or map. There are two ways you can create a dictionary. You can start with an empty dictionary and add key-value pairs or you can enumerate key-value pairs. The syntax for doing so is shown below:

  phone_book = {}
  phone_book['Mickey Mouse'] = '409-896-4861'
  phone_book['Donald Duck'] = '409-896-5007'

  phone_book = {'Mickey Mouse':'409-896-4861', 'Donald Duck':'409-896-5007'}
Since keys are unique, you can always extract the value by using the key as the index. However, you cannot get the key easily if you just know the value, since values are not unique. You can also assign values if you know the key. If the key does not exist, a new key-value pair is created in the dictionary. If the key already exists, the old value gets over-written. To iterate through all the entries in a dictionary you can do:
  for key in dict:
    print dict[key]

There are several built-in functions that makes it easy to manipulate a dictionary.
Function Meaning
dict.has_key (key) Returns True if the dictionary contains the specified key and False otherwise.
key in dict Returns True if the dictionary contains the specified key and False otherwise.
dict.keys() Returns a list of keys.
dict.values() Returns a list of values.
dict.items() Returns a list of tuples representing key-value pairs.
dict.get (key, default) If the dictionary has the key it returns the value, otherwise it returns the default value.
del dict[key] Deletes the specified entry.
dict.clear() Deletes all entries.

Input / Output

You can prompt the user to enter a number by using function input() or a string by using the function raw_input(). The function then waits for the user to enter the value and reads what has been typed only after the user has typed the Enter or Return key. The value is then assigned to a variable of your choosing.

n = input ("Enter a number: ")

name = raw_input ("Enter your name: ")

The print command allows you to print out the value of a variable. If you want to add text to the output, then that text has to be in single or double quotes. The comma (,) is used as the concatentation operator.

print 'n = ', n
print "name = ", name

Files

It is relatively simple to to do file manipulation in Python. To process a file it has to be opened. Python offers 3 modes for opening a file - read ("r"), write ("w"), and append ("a"). The syntax for opening a file is as follows:

  fileVar = open ("fileName", "mode")

For example,

  inFile = open ("input.txt", "r")

To close a file simply do

  inFile.close()

To read a file, the file must not only exist but also have read permissions. Whereas, if the file does not exist in the write mode a new file with that name is created. If you open a file in write mode and there is already an existing file then the original contents get over-written. If you wish to preserve the original content and still write to the file then open it in append mode. Files must be closed at the end of the operation.

Reading a Text File

You have several options in reading a file. If the file is small then it can be read in as a single string. The command to do so is read().

  infile = open ("input.txt", "r")
  fileContent = infile.read()
However, if the file is too large to fit in memory, then you will have to read the file line by line. The command to do so is readline(). This will read in all characters including the terminating newline character. To read remaining lines in the file you can use the command readlines(). The simplest way to read a file line by line would be to:
  infile = open ("input.txt", "r")
  for line in infile:
    #  process the line
    line = line.rstrip("\n")   # strip the newline character at the end
    ...
  infile.close()

Writing / Appending to a Text File

To write to a file, the files must be opened for writing. If it is opened in "w" mode then the previous content will be overwritten. If it is opened in "a" mode then the new content will added to the end of the previous content. Python provides the command write() to write or append to a file. You must explicitly add the newline character (\n) to the end of each line.

  outfile = open ("output.txt", "w")
  outfile.write ("This is a line. \n")
  outfile.close()
The write() function takes a string as input parameter.

Python Links

Python Tutorials and Books

Miscellaneous Information on Python