You are on page 1of 38


Spring 2017


Diwakar Raja Anbarasu
Table of contents

A. PL Research: Python
1. History ……………………………………………… 4
2. Paradigm/Classification …………………………….. 5
3. Compilers…………………………………………… 7
4. Applications………………………………………….. 11
5. Program Structure……………………………………..13
6. Data Types/Objects……………………………………17
7. Sequence Control………………………………...……20
8. Input/Output…………………………………………..22
9. Sup-program Control…………………………………24
10. Encapsulation/Inheritance…………………………..26
11. Example of a Simple Program……………………...27

B. Programming Project: Home of Python

2.List of Question and Answers………………………29
3.Program Structure (CGIapplet) Diagram……………30
4.List and Diagram of Programs………………………32
5. Examples (print windows step by step)……………..33

A. PL Research: Python
1. History
Python was conceived in the late 1980’s by Guido van Rossum who was conducting research
on programming languages at Centrum Wiskunde & Informatica in the Netherlands, a research
institution which concentrates on Mathematics and Computer science. Guido wanted to create a
new programming language during his free time in the weekends and he started his work on
python. He took inspiration from an existing programming language called ABC which was a
general purpose programming language which was used at CWI. Although it was not very
popular and CWI stopped further development of ABC. Python borrows features from ABC and
the syntax and semantics are influenced by MODULA 2+ and MODULA 3.

It was developed with a few core philosophies which can be summarized by

 Beautiful is better than ugly
 Explicit is better than implicit
 Simple is better than complex
 Complex is better than complicated
 Readability counts

Following these principles python would rise to popularity, although not popular until the
mid 2000s since only a handful of people were using it. Python saw a major mainstream success
in the late 2000s since google started using it as an implementation language. Now python can be
seen everywhere since it is portable across all major hardware and software platforms and it also
has a lot of libraries and frameworks which makes it really easy to program with.


There are several implementations of python, namely

 PyPy (written in Python)
 CPython (written in C)
 IronPython (written in C#)
 Jython (written in Java)
 Stackless Python (Branch of CPython)

How ever the default or the traditional implementation is CPython written in C. The first public
version of python was released on February 20, 1991 labeled as version 0.9.0

Version 1:

In 1994 python reached version 1.0 including a new set of features which included some
functional programming tools like reduce(), map(), filter() and patches.

From version 1.4 – version 1.6 python got several updates inspired from MODULA-3’s keyword
arguments and built-in support for complex numbers and fixed a lot of bugs from the previous

Version 2:

Version 2.0 introduced new features like list comprehension, which was inspired from
other programming languages like SETL and Haskell. The python syntax was also inspired from
Haskell and this version also introduced a garbage collection system.

During version 2.1- 2.2 python unified its types which are written in C and the classes which are
written and python into one hierarchy which made python’s object model into object oriented.

Version 2.7 was the last version 2 release and it had features very similar to version 3.0 and 3.1

Version 3:

Version 3.0 was released on December 2008 which was designed in a way to patch the
design flaws of the previous versions and improving backwards compatibility. Version 3 is still
getting updates to this date with the current release labeled Python 3.6.1, released on 21 March

2. Paradigm/Classification:
Python supports multiple paradigms. It can be Object-oriented, imperative, functional,
procedural and reflective.

Although python is classified into all these paradigms its much stronger in some paradigms than
the others. It is called a interpreted or a scripting language, in boarder sense it is an imperative
programming language rather than a declarative (functional) language. It is dynamically and
strongly typed.

Although its more object oriented the syntax allows procedural flow style. It is very flexible with

3. Compilers:
Python source code is automatically compiled into Python byte code by the CPython
interpreter. Compiled code is usually stored in PYC (or PYO) files, and is regenerated when the
source is updated, or when otherwise necessary.Lot of compilers are available for different kinds
of uses.



You feed it your Python app, it does a lot of clever things, and spits out an executable or
extension module.

Free license (Apache).

Download from:


pyjs is a Rich Internet Application (RIA) Development Platform for both Web and Desktop. With
pyjs you can write your JavaScript-powered web applications entirely in Python.

Free license (Apache).

Download from:

Most of the python compilers are free and is covered by the Python Software Foundation
Even though python is used commercially there are no compilers that requires a paid license

 Python is absolutely free, even for commercial use (including resale). You can sell a
product written in Python or a product that embeds the Python interpreter. No licensing
fees need to be paid for such usage.

 The Open Source Initiative has certified the Python license as Open Source, and includes
it on their list of open source licenses.

 There is no GPL-like "copyleft" restriction. Distributing binary-only versions of Python,
modified or not, is allowed. There is no requirement to release any of your source code.
You can also write extension modules for Python and provide them only in binary form.

 However, the Python license is compatible with the GPL, according to the Free Software

 You cannot remove the PSF's copyright notice from either the source code or the
resulting binary.

4. Applications:
Web and Internet Development:

Python offers many choices for web development:

 Frameworks such as Django and Pyramid.
 Micro-frameworks such as Flask and Bottle.
 Advanced content management systems such as Plone and django CMS.
 Python's standard library supports many Internet protocols:

 HTML and XML
 E-mail processing.
 Support for FTP, IMAP, and other Internet protocols.
 Easy-to-use socket interface.

Scientific and Numeric:

Python is widely used in scientific and numeric computing:
 SciPy is a collection of packages for mathematics, science, and engineering.
 Pandas is a data analysis and modeling library.
 IPython is a powerful interactive shell that features easy editing and recording of a work
session, and supports visualizations and parallel computing.
 The Software Carpentry Course teaches basic skills for scientific computing, running
bootcamps and providing open-access teaching materials.

Software Development:

Python is often used as a support language for software developers, for build control and
management, testing, and in many other ways.
 SCons for build control.
 Buildbot and Apache Gump for automated continuous compilation and testing.
 Roundup or Trac for bug tracking and project management.

GUI Development:

Build a GUI application (desktop app) using Python modules Tkinter, PyQt to support it.

Rapid Prototyping:

Python has libraries for just about everything. Use it to quickly built a (lower-
performance, often less powerful) prototype. Python is also great for validating ideas or products
for established companies and start-ups alike.

Writing Scripts:

If you're doing something manually and want to automate repetitive stuff, such as emails,
it's not difficult to automate once you know the basics of this language.

Data Analysis:

Python is the leading language of choice for many data scientists. Python has grown in
popularity, within this field, due to its excellent libraries including; NumPy and Pandas and its
superb libraries for data visualisation like Matplotlib and Seaborn.

5. Program Structure:

Credits: This guide was created by David Faulkner, Dan Upton, and David Evans for CS150
Fall 2005. It was revised for CS 150 in Spring 2009 by Westley Weimer.

The program is structured with blocks and indentations are used to specify a block of code.
Variables are initialized first before they are used. Functions also use indentations to specify the
start and the end of a function block.
As long as they are indented properly the program can have as many parts the programmers
intend it to.

A familiar example:

We can see how login.cgi that we use later in the project is structured with importing modules
first, then variable initializations followed by blocks of codes and functions. Here we also
encounter multiple single line code used to print html.

6. Data types:

Python has five standard Data Types:

 Numbers

 String

 List

 Tuple

 Dictionary

 Boolean

Type Format Description
int a = 10 Signed Integer
long a = 345L (L) Long integers, they can also be represented in octal and hexadecimal

float a = 45.67 (.) Floating point real values

complex a = 3.14J (J) Contains integer in the range 0 to 255.

Any number you enter in Python will be interpreted as a number; you are not required to
declare what kind of data type you are entering. Python will consider any number written without
decimals as an integer (as in 138) and any number written with decimals as a float (as in 138.0).


The Boolean data type can be one of two values, either True or False

We can declare them as following


Another special data type we have to know about is none.

None: Often written null in other languages, it is usually used to represent 'nothing'.
It can be declared as

x = None

Create string variables by enclosing characters in quotes. Python uses single quotes '
double quotes "and triple quotes """ to denote literal strings. Only the triple quoted strings """
also will automatically continue across the end of line statement.

How to declare:

firstName = 'john'
lastName = "smith"
message = """This is a string that will span across multiple lines. Using newline characters
and no spaces for the next lines. The end of lines within this string also count as a newline when


Lists are a very useful variable type in Python. A list can contain a series of values. List
variables are declared by using brackets [ ] following the variable name.

# w is an empty list

# x has only one member

# y is a list of numbers

# z is a list of strings
# and other lists


Tuples are a group of values like a list and are manipulated in similar ways. But, tuples
are fixed in size once they are assigned. In Python the fixed size is considered immutable as
compared to a list that is dynamic and mutable. Tuples are defined by parenthesis ().


myGroup = ('Rhino', 'Grasshopper', 'Flamingo', 'Bongo')


A Python dictionary is a group of key-value pairs. The elements in a dictionary are indexed by
keys. Keys in a dictionary are required to be unique.


words = { 'girl': 'Maedchen', 'house': 'Haus', 'death': 'Tod' }

User defined data types :

Classes and Objects

Objects are an encapsulation of variables and functions into a single entity. Objects get their
variables and functions from classes. Classes are essentially a template to create your objects.

source :

The variable "myobjectx" holds an object of the class "MyClass" that contains the variable and
the function defined within the class called "MyClass".

To access a function inside of an object you use notation similar to accessing a variable:

7. Sequence control:


An expression is an instruction that combines values and operators and always evaluates down
to a single value.

For example, this is an expression:



A Python statement is pretty much everything else that isn't an expression. Here's
an assignment statement:

spam = 2 + 2

Conditional statements:

if Statements:

Perhaps the most well-known statement type is the if statement. For example:

if temp < 10:
print "It is cold!"


It is cold!

if…else statement:

temp = 20

if temp < 10:
print "It is cold!"
print "It feels good!“


It feels good!

for Statements:

The for statement in Python differs a bit from what you may be used to in C or Pascal.

Python’s for statement iterates over the items of any sequence (a list or a string), in the order that
they appear in the sequence. For example

for i in [0,1,2,3,4]:
print i



While loops:

A while loop repeats a sequence of statements until some condition becomes false. For example:

while x > 0:
print (x)



Breaking and continuing:

Python includes statements to exit a loop (either a for loop or a while loop) prematurely. To exit a
loop, use the break statement:

while x > 0:
print x
x -= 1
print x



Continue statement:

The continue statement is used in a while or for loop to take the control to the top of the loop
without executing the rest statements inside the loop. Here is a simple example.

for x in range(6):
if (x == 3 or x==6):



8. Input/Output:

There will be situations where your program has to interact with the user. For example,
you would want to take input from the user and then print some results back. We can achieve
this using the input()function and print function respectively.


something = input("Enter text: ")



Enter text: sir

File input and output:

Reading Text from a File:

In order to read and write a file, Python built-in function open() is used to open the file.
The open()function creates a file object.


file object = open(file_name [, access_mode])
First argument file_name represents the file name that you want to access.
Second argument access_mode determines, in which mode the file has to be opened, i.e., read,
write, append, etc.
Access_mode for reading, is 'r' . The program reads a simple text file i created on my system
using text editor. Here are the contents of the file.


file_input = open("simple_file.txt",'r')
all_read =

print all_read



Writing Text to a File:

In this section we will discuss write a file with Python. This time we will use write mode "w"
in open()function.
We will use write() function.

Let us discuss our example.

text_file = open("writeit.txt",'w')



9.Sup-program Control:

Built-in Functions:

Functions like print(), input(), eval() etc. that we have been using, are some examples of the
built-in function. There are 68 built-in functions defined in Python 3.5.2. They are listed below
alphabetically along with a brief description.

Built-in Functions

abs() dict() help() min() setattr()

all() dir() hex() next() slice()

any() divmod() id() object() sorted()

ascii() enumerate() input() oct() staticmethod()

bin() eval() int() open() str()

Built-in Functions

bool() exec() isinstance() ord() sum()

bytearray() filter() issubclass() pow() super()

bytes() float() iter() print() tuple()

callable() format() len() property() type()

chr() frozenset() list() range() vars()

classmethod() getattr() locals() repr() zip()

compile() globals() map() reversed() __import__()

complex() hasattr() max() round()

delattr() hash() memoryview() set()
Source :

User defined Functions:

Defining Functions

A function is defined in Python by the following format:

def functionname(arg1, arg2, ...):


def functionname(arg1,arg2):
return arg1+arg2

t = functionname(24,24) # Result: 48


If a function takes no arguments, it must still include the parentheses, but without anything in

def functionname():

Default Parameters

Having parameters is great, but it can be repetitive to continue to use them over and over, again.
We can define a default value for a parameter by setting its value when you define the parameter.
Take the script below for example.

def woof(x=0):


The output should be:


Variable-Length Argument Lists

Python allows you to declare two special arguments which allow you to create arbitrary-length
argument lists. This means that each time you call the function, you can specify any number of
arguments above a certain number.

def function(first,second,*remaining):


When calling the above function, you must provide value for each of the first two arguments.
However, since the third parameter is marked with an asterisk, any actual parameters after the
first two will be packed into a tuple and bound to "remaining."

def print_tail(first,*tail):
print tail
print_tail(1, 5, 2, "omega")



Python has the ability to return multiple values from a function call, something missing from
many other languages. In this case the return values should be a comma-separated list of values
and Python then constructs a tuple and returns this to the caller.


def square(x,y):
return x*x, y*y

t = square(2,3)
print t



10. Encapsulation/Inheritance:


In an object oriented python program, you can restrict access to methods and variables.
This can prevent the data from being modified by accident and is known as encapsulation. Let’s
start with an example.

If an identifier doesn't start with an underscore character "_" it can be accessed from
outside, i.e. the value can be read and changed. Data can be protected by making members
private or protected. Instance variable names starting with two underscore characters cannot be
accessed from outside of the class.

Public variables:


>>> class Foo:
def __init__(self): = 1

>>> foo = Foo()


Private variables:

>>> class Foo:
def __init__(self):
self.__bar = 1

>>> foo = Foo()
>>> foo.__bar

output :


The private variable __bar cannot be accessed by objects outside the class. So when you run the
program you will get an error:

Private Methods:

Methods can be made private in the same way, by naming them with two leading underscores
and no trailing underscores.

>>> class Foo(object):
def __init__(self):
self.__hello = "Hello"
def __say_hello(self):
def say_hello(self):

>>> foo = Foo()
>>> foo.__say_hello()



We cannot access private methods that are declared private inside the object. So we get an error
when we try to execute the code.

Inheritance in Python:

Inheritance is used to inherit another class' members, including fields and methods. A sub class
extends a super class' members.


class SubClass(BaseClass):
def some_method(self, passed_params):
#calling base class version of method
BaseClass.some_method(self, passed_params)


class Cat(object):
def __init__(self, name): = "Garfield"

def sound(self):
return "Meow"

class Tiger(Cat):
def __init__(self, name): #will overwrite Cat constructor = "Mike Tyson Jr."

def sound(self): #will overwrite the Cat sound method
return "Roar"

def cat_sound():
Cat.sound() #will call cat's sound

11. Example of a Simple Program:


# This program adds two numbers

num1 = 1.5
num2 = 6.3

# Add two numbers
sum = num1 + num2

# Display the sum


A. Programming Project: Home of Python


2.List of Question and Answers

Dialog -1 :

Question 1: Do you like python?

Possible Answers – 1:
o NO! not at all
o YES! very much
o I guess..
Dialog – 2:
(if answer-1 is NO! not at all)

Sorry to hear that your choice was - NO! not at all

Question 2: So why was it NO! not at all?

Possible Answers – 2:
 Its hard!
 I like javascript more!
 I like more lines of code!

(if answer is YES! very much)

Happy to hear that you Choose - YES! very much

Question 2: Care to share why you said YES! very much?

Possible answer – 2:
 Its so easy!
 I like snakes!
 so portable!

(if answer is I guess..)

Are you sure?

Question 2: Why was it I guess..?

Possible answer – 2:

 not so interesting
 Can't say why

 Stop asking me so many questions!

3.Program Structure (CGIapplet) Diagram

4.List and Diagram of Programs

List of programs:

Diagram of programs:

Database MYSQL
<table UserPass>

UserName Password
abc 1234
aa bbb

Examples: (step by step pictures)


Leant about python from the programming language research
Learnt HTML and python and how to use forms and link databases using python
Used perl to create a chat
Learnt how to use java applets