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 It will have a single statement - print "Hello World!" . To run your program, type at the command line

> python

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

print "Hello World!"

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

> chmod +x

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

> ./

First Program in Java

public class Hello
  public static void main (String[] args)
    System.out.println ("Hello World!");

To compile and run the program you do:


java Hello

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.


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


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.


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:


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


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):
The body of if, elif, and else parts need to be indented.


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):

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):
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):
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):
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]:


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]):
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
        n = n - m
    return m

  def coPrime (a, b):
    if (gcd(a, b) != 1):
      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)



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.

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

Python Links

Python Tutorials and Books

Miscellaneous Information on Python