PP Lab Manual
PP Lab Manual
Theory
Programming languages provide various control structures that allow for more complicated
execution paths. A loop statement allows us to execute a statement or group of statements
multiple times. The following diagram illustrates a loop statement:
While loop
Syntax: The syntax of a while loop in Python programming language is:
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following
the loop.
count = 0
while (count < 3):
print 'The count is:', count
count = count + 1
print "Good bye!"
When the above code is executed, it produces the following result:
If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence
is assigned to the iterating variable iterating_var. Next, the statements block is executed. Each
item in the list is assigned to iterating_var, and the statement(s) block is executed until the
entire sequence is exhausted.
Example
for letter in 'Python': # First Example
print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
Nested Loops
Python programming language allows to use one loop inside another loop. Following section
shows few examples to illustrate the concept.
Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is as follows:
while expression:
while expression:
statement(s)
statement(s)
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100:
i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) : print i, " is prime"
i=i+1
print "Good bye!"
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. Python supports the
following control statements. Click the following links to check their detail.
Syntax
The syntax for a break statement in Python is as follows:
Break
Example
for letter in 'Python': # First Example
if letter == 'h':
break
print 'Current Letter :', letter
When the above code is executed, it produces the following result:
Current Letter : P
Current Letter : y
Current Letter : t
Continue Statement
It returns the control to the beginning of the while loop. The continue statement rejects all the
remaining statements in the current iteration of the loop and moves the control back to the top
of the loop. The continue statement can be used in both while and for loops.
Syntax
Continue
Example
for letter in 'Python': # First Example
if letter == 'h':
continue
print 'Current Letter :', letter
When the above code is executed, it produces the following result:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Pass Statement
It is used when a statement is required syntactically but you do not want any command or code
to execute. The pass statement is a null operation; nothing happens when it executes. The pass
is also useful in places where your code will eventually go, but has not been written yet (e.g.,
in stubs for example):
Syntax
Pass
Exercise:
1. Develop a program to check whether a given number is even or not.
2. To find the maximum of a list of numbers given.
3. Develop program to find the Factorial of a given Number.
4. Develop a program to check whether a given number is Armstrong or not.
Review Question:
1. Differentiate between break and continue statement.
2. How nested loop is used in Python?
Theory
Variables are nothing but reserved memory locations to store values. This means when you
create a variable, you reserve some space in memory. Based on the data type of a variable, the
interpreter allocates memory and decides what can be stored in the reserved memory.
Therefore, by assigning different data types to variables, you can store integers, decimals, or
characters in these variables.
Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables. The operand to the left of the = operator is the name of the variable
and the operand to the right of the = operator is the value stored in the variable.
Standard Data Types
The data stored in memory can be of many types. For example, a person's age is stored as a
numeric value and his or her address is stored as alphanumeric characters. Python has various
standard data types that are used to define the operations possible on them and the storage
method for each of them.
Python has five standard data types:
Numbers
String
List
Tuple
Dictionary
Python Lists
Lists are the most versatile of Python's compound data types. A list contains items separated
by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays
in C. One difference between them is that all the items belonging to a list can be of different
data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is
the list concatenation operator, and the asterisk (*) is the repetition operator.
Example
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
Python Dictionary
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python
object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]).
For example
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values
Exercise:
1. Write a Python script to print a dictionary where the keys are numbers between 1 and
15 (both included) and the values are square of keys. Sample Dictionary: {1: 1, 2: 4, 3:
9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15:
225}
2. Develop a program to check given number is prime or not using tuple.
3. Write a Python program to get the smallest number from a list.
4. Develop a Python Program to Find the Largest Number among Three Numbers using
tuple.
5. Write a Python program to sort a dictionary by key.
6. Write a Python program to remove duplicates from Dictionary.
Review Question:
1. What’s The Difference Between The Python append() and extend() Methods?
2. How to concatenate list?
3. How to sort a list?
4. How to remove duplicates from a tuple?
Theory
Scope
In the section above, we have learned that namespaces can exist independently from each other
and that they are structured in a certain hierarchy, which brings us to the concept of “scope”.
The “scope” in Python defines the “hierarchy level” in which we search namespaces for certain
“name-to-object” mappings.
For example, let us consider the following code:
i=1
def foo():
i=5
print(i, 'in foo()')
print(i, 'global')
foo()
1 global
5 in foo()
We have seen that multiple namespaces can exist independently from each other and that they
can contain the same variable names on different hierarchy levels. The “scope” defines on
which hierarchy level Python searches for a particular “variable name” for its associated object.
Now, the next question is: “In which order does Python search the different levels of
namespaces before it finds the name-to-object’ mapping?”
To answer is: It uses the LEGB-rule, which stands for
Local -> Enclosed -> Global -> Built-in,
Where the arrows should denote the direction of the namespace-hierarchy search order.
Local can be inside a function or class method, for example.
Enclosed can be its enclosing function, e.g., if a function is wrapped inside another function.
Global refers to the uppermost level of the executing script itself, and
Built-in are special names that Python reserves for itself.
Definition of Recursion
Recursion is a way of programming or coding a problem, in which a function calls itself one
or more times in its body. Usually, it is returning the return value of this function call. If a
function definition fulfils the condition of recursion, we call this function a recursive function.
Termination condition
A recursive function has to terminate to be used in a program. A recursive function terminates,
if with every recursive call the solution of the problem is downsized and moves towards a base
case. A base case is a case, where the problem can be solved without further recursion. A
recursion can lead to an infinite loop, if the base case is not met in the calls.
Example
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1
Replacing the calculated values gives us the following expression
4! = 4 * 3 * 2 * 1
Generally we can say: Recursion in computer science is a method where the solution to a
problem is based on solving smaller instances of the same problem.
Recursive Functions in Python
Exercise:
1. Write a Python function to find the Max of three numbers.
2. Write a Python function to sum all the numbers in a list.
3. Write a Python program to reverse a string.
4. Write a Python function to check whether a number is in a given range.
5. Write a Python function that accepts a string and calculate the number of upper case
letters and lower case letters.
6. Write a Python function that takes a list and returns a new list with unique elements of
the first list
7. Write a Python program to access a function inside a function.
Review Question:
1. Differentiate between global and local variables.
2. How to access a global variable form a function?
3. How nested function is implement in Python?
Theory
Python provides two very important features to handle any unexpected error in your Python
programs and to add debugging capabilities in them −
Exception Handling − This would be covered in this tutorial. Here is a list standard
Exceptions available in Python: Standard Exceptions.
1 Exception
Base class for all exceptions
2 StopIteration
Raised when the next() method of an iterator does not point to any object.
3 SystemExit
Raised by the sys.exit() function.
4 StandardError
Base class for all built-in exceptions except StopIteration and SystemExit.
5 ArithmeticError
Base class for all errors that occur for numeric calculation.
6 OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.
7 FloatingPointError
Raised when a floating point calculation fails.
8 ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric types.
9 AssertionError
Raised in case of failure of the Assert statement.
10 AttributeError
Raised in case of failure of attribute reference or assignment.
11 EOFError
Raised when there is no input from either the raw_input() or input() function and the end of
file is reached.
12 ImportError
Example
This example opens a file, writes content in the, file and comes out gracefully because there
is no problem at all −
#!/usr/bin/python
try:
fh = open("testfile", "w")
except IOError:
else:
fh.close()
Example
This example tries to open a file where you do not have write permission, so it raises an
exception −
#!/usr/bin/python
try:
fh = open("testfile", "r")
except IOError:
else:
Exercise:
1. Write a Python program which will demonstrate the exception handling.
2. Write a Python program to implement user defined exceptions.
Review Question:
1. What is the use of exceptions in Python?
2. What is the keyword used after the try statement to handle exceptions?
3. Explain try and finally clause of exception in Python.
Theory
Searching is the algorithmic process of finding a particular item in a collection of items. A
search typically answers either True or False as to whether the item is present. On occasion it
may be modified to return where the item is found. For our purposes here, we will simply
concern ourselves with the question of membership.
In Python, there is a very easy way to ask whether an item is in a list of items. We use the in
operator.
>>> 15 in [3,5,2,4,1]
False
>>> 3 in [3,5,2,4,1]
True
>>>
Even though this is easy to write, an underlying process must be carried out to answer the
question. It turns out that there are many different ways to search for the item. What we are
interested in here is how these algorithms work and how they compare to one another.
Hashing
In previous sections we were able to make improvements in our search algorithms by taking
advantage of information about where items are stored in the collection with respect to one
another. For example, by knowing that a list was ordered, we could search in logarithmic time
using a binary search. In this section we will attempt to go one step further by building a data
structure that can be searched in O(1)O(1) time. This concept is referred to as hashing.
A hash table is a collection of items which are stored in such a way as to make it easy to find
them later. Each position of the hash table, often called a slot, can hold an item and is named
by an integer value starting at 0. For example, we will have a slot named 0, a slot named 1, a
slot named 2, and so on. Initially, the hash table contains no items so every slot is empty. We
can implement a hash table by using a list with each element initialized to the special Python
value None. Figure shows a hash table of size m=11m=11. In other words, there are m slots in
the table, named 0 through 10.
The mapping between an item and the slot where that item belongs in the hash table is called
the hash function. The hash function will take any item in the collection and return an integer
in the range of slot names, between 0 and m-1. Assume that we have the set of integer items
54, 26, 93, 17, 77, and 31. Our first hash function, sometimes referred to as the “remainder
method,” simply takes an item and divides it by the table size, returning the remainder as its
hash value (h(item)=item%11h(item)=item%11). Table gives all of the hash values for our
example items. Note that this remainder method (modulo arithmetic) will typically be present
in some form in all hash functions, since the result must be in the range of slot names.
54 10
26 4
93 5
17 6
77 0
31 9
Another numerical technique for constructing a hash function is called the mid-square method.
We first square the item, and then extract some portion of the resulting digits. For example, if
the item were 44, we would first compute 442=1,936442=1,936. By extracting the middle two
digits, 93, and performing the remainder step, we get 5 (93 % 1193 % 11). Table shows items
under both the remainder method and the mid-square method. You should verify that you
understand how these values were computed.
54 10 3
26 4 7
93 5 9
17 6 8
77 0 4
31 9 6
We can also create hash functions for character-based items such as strings. The word “cat”
can be thought of as a sequence of ordinal values.
>>> ord('c')
99
>>> ord('a')
97
>>> ord('t')
116
Sorting
Sorting is the process of placing elements from a collection in some kind of order. For example,
a list of words could be sorted alphabetically or by length. A list of cities could be sorted by
population, by area, or by zip code. We have already seen a number of algorithms that were
Exercise:
1. Write a Python program to sort a list of elements using the bubble sort algorithm.
2. Write a Python program to sort a list of elements using the selection sort algorithm.
3. Write a Python program to sort a list of elements using the insertion sort algorithm.
4. Write a Python program to sort a list of elements using the merge sort algorithm.
5. Write a Python program for counting sort.
Review Question:
1. What is hash function in Python?
2. What is rehashing in hash table?
Theory
A regular expression is a special sequence of characters that helps you match or find other
strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are
widely used in UNIX world.
1 Pattern
This is the regular expression to be matched.
2 String
This is the string, which would be searched to match the pattern at the beginning
of string.
3 Flags
You can specify different flags using bitwise OR (|). These are modifiers, which
are listed in the table below.
1 group(num=0)
This method returns entire match (or specific subgroup num)
2 groups()
This method returns all matching subgroups in a tuple (empty if there weren't
any)
Example
#!/usr/bin/python
import re
if matchObj:
else:
1 Pattern
This is the regular expression to be matched.
2 String
This is the string, which would be searched to match the pattern anywhere in the
string.
3 Flags
You can specify different flags using bitwise OR (|). These are modifiers, which
are listed in the table below.
1 group(num=0)
This method returns entire match (or specific subgroup num)
2 groups()
This method returns all matching subgroups in a tuple (empty if there weren't
any)
#!/usr/bin/python
import re
if searchObj:
else:
#!/usr/bin/python
import re
if matchObj:
else:
if searchObj:
else:
#!/usr/bin/python
import re
Exercise:
1. Write a Python program to check that a string contains only a certain set of characters
2. Write a Python program that matches a string that has an a followed by zero or more
b's.
3. Write a Python program to find sequences of lowercase letters joined with a underscore.
4. Write a Python program that matches a word at the beginning of a string.
Review Question:
1. Which module in Python support regular expression?
2. What does the function re.search do?
3. What does the function re.match do?
Theory
Simple Chat Room using Python
Socket programming
Sockets can be thought of as endpoints in a communication channel that is bi-directional, and
establishes communication between a server and one or more clients. Here, we set up a socket
on each end and allow a client to interact with other clients via the server. The socket on the
server side associates itself with some hardware port on the server side. Any client that has a
socket associated with the same port can communicate with the server socket.
Multi-Threading
A thread is sub process that runs a set of commands individually of any other thread. So,
every time a user connects to the server, a separate thread is created for that user and
communication from server to client takes place along individual threads based on socket
objects created for the sake of identity of each client.
We will require two scripts to establish this chat room. One to keep the serving running, and
another that every client should run in order to connect to the server.
Review Question:
1. Explain what Client Side Script & Server side Script?
2. Want is the usage of multithreading?
.
Theory
PyLab is a Python standard library module that provides many of the facilities of MATLAB,
“a high-level technical computing language and interactive environment for algorithm
development, data visualization, data analysis, and numeric computation.”57 Later in the
book, we will look at some of the more advanced features of PyLab, but in this chapter we
focus on some of its facilities for plotting data. A complete user’s guide for PyLab is at the
Web site matplotlib.sourceforge.net/users/index.html. There are also a number of Web sites
that provide excellent tutorials. We will not try to provide a user’s guide or a complete tutorial
here. Instead, in this chapter we will merely provide a few example plots and explain the code
that generated them. Other examples appear in later chapters. Let’s start with a simple
example that uses pylab.plot to produce two plots. Executing import pylab pylab.figure(1)
#create figure 1 pylab.plot([1,2,3,4], [1,7,3,5]) #draw on figure 1 pylab.show() #show figure
on screen will cause a window to appear on your computer monitor. Its exact appearance may
depend on the operating system on your machine, but it will look similar to the following:
The bar at the top contains the name of the window, in this case “Figure 1.” The middle
section of the window contains the plot generated by the invocation of pylab.plot. The two
parameters of pylab.plot must be sequences of the same length. The first specifies the x-
coordinates of the points to be plotted, and the second specifies the y-coordinates. Together,
they provide a sequence of four coordinate pairs, [(1,1), (2,7), (3,3), (4,5)]. These are plotted
in order. As each point is plotted, a line is drawn connecting it to the previous point. The final
line of code, pylab.show(), causes the window to appear on the computer screen.58 If that
line were not present, the figure would still have been produced, but it would not have been
displayed. This is not as silly as it at first sounds, since one might well choose to write a figure
directly to a file, as we will do later, rather than display it on the screen. The bar at the bottom
of the window contains a number of push buttons. The rightmost button is used to write the
plot to a file.59. The next button to the left is used to adjust the appearance of the plot in the
window. The next four buttons are used for panning and zooming. And the button on the left
pylab.figure(1) #go
back to working on
figure 1
pylab.plot([5,6,10,3]) #draw again on figure 1
pylab.savefig('Figure-Jane') #save figure 1
produces and saves to files named Figure-Jane.png and Figure-Addie.png the two
plots below.
However, this cannot be easily inferred by looking only at the plot itself. That’s a bad thing.
All plots should have informative titles, and all axes should be labeled.
If we add to the end of our the code the lines
pylab.title('5% Growth, Compounded Annually')
pylab.xlabel('Years of Compounding')
pylab.ylabel('Value of Principal ($)')
we get the plot above and on the right.
For every plotted curve, there is an optional argument that is a format string indicating the color
and line type of the plot.60 The letters and symbols of the format string are derived from those
used in MATLAB, and are composed of a color indicator followed by a line-style indicator.
The default format string is 'b-', which produces a solid blue line. To plot the above with red
circles, one would replace the call pylab.plot(values) by pylab.plot(values, 'ro'), which
produces the plot on the right. For a complete list of color and line-style indicators. It’s also
possible to change the type size and line width used in plots. This can be done using keyword
arguments in individual calls to functions, e.g., the code
principal = 10000 #initial investment
interestRate = 0.05
Review Question:
1. What is PyPlot? How it is used?
2. Describe different graphs can be plotted using PyPlot.
3. Give any example of graph plotted using PyPlot with code.
Theory
The reverse cipher always encrypts the same way. But the Caesar cipher uses keys, which
encrypt the message in a different way depending on which key is used. The keys for the Caesar
cipher are the integers from 0 to 25. Even if a cryptanalyst knows that the Caesar cipher was
used, that alone does not give her enough information to break the cipher. She must also know
the key.
C o M m o n (s) s
We only have 8 boxes but there are 30 characters in the message. When you run out of
boxes, draw another row of 8 boxes under the first row. Keep creating new rows until you
have written out the full message:
1st 2nd 3rd 4th 5th 6th 7th 8th
C o m m o n (s) s
e n s e (s) i s (s)
n o t (s) s o (s) c
o m m o n .
We shade in the two boxes in the last row to remind us to ignore them. The ciphertext is the
letters read from the top left box going down the column. “C”, “e”, “n”, and “o” are from the
1st column. When you get to the last row of a column, move to the top row of the next
column to the right. The next characters are “o”, “n”, “o”, “m”. Ignore the shaded boxes.
The ciphertext is “Cenoonommstmme oo snnio. s s c”, which is sufficiently scrambled to keep
someone from figuring out the original message by looking at it.
(Note that if the length divided by the key was a whole number, like in 30 / 5 = 6.0, then 6.0
would not “round up” to 7.)
Then start filling in the boxes with one character of the ciphertext per box. Start at the top left
and go right, just like we did when we were encrypting. The ciphertext is “Cenoonommstmme
oo snnio. s s c”, and so “Ceno” goes in the first row, then “onom” in the second row, and so
on. After we are done, the boxes will look like this (where the (s) represents a space):
C e n O
o n o M
m s t M
m e (s) O
o (s) s N
n i o .
(s) s (s)
s (s) c
Our friend who received the ciphertext will see that if she reads the text going down the
columns, the original plaintext has been restored: “Common sense is not so common.”
Exercise:
1. Write a Python program to implement Classical cipher.
2. Write a Python program to implement Ceaser cipher.
3. Write a Python program to implement Reverse cipher.
4. Write a Python program to implement Transposition cipher.
Review Question:
1. List different classical cipher in details.
2. Explain reverse cipher with an example.
3. Explain ceaser cipher with an example.
4. Explain encrypting and decrypting the transposition cipher.
Demo scripts
There is a set of demo scripts in the turtledemo directory located in the Demo/turtle directory
in the source distribution.
It contains:
a set of 15 demo scripts demonstrating different features of the new module turtle
a demo viewer turtleDemo.py which can be used to view the source code of the scripts
and run them at the same time. 14 of the examples can be accessed via the Examples
menu; all of them can also be run standalone.
The example turtledemo_two_canvases.py demonstrates the simultaneous use of two
canvases with the turtle module. Therefore it only can be run standalone.
There is a turtle.cfg file in this directory, which also serves as an example for how to
write and use such files.
The demo scripts are:
Rectangular Turtles as
minimal_hanoi Towers of Hanoi Hanoi discs (shape,
shapesize)
compound
planet_and_moon simulation of gravitational system
shapes, Vec2D
Review Question:
1. Explain different methods of turtle graphics.
2. List turtle’s state different methods.
We are using three widgets: Tk is the class which we use to create the root window – the main
window of our application. Our application should only have one root, but it is possible for us
to create other windows which are separate from the main window.
Widget classes
There are many different widget classes built into tkinter – they should be familiar to you from
other GUIs:
A Frame is a container widget which is placed inside a window, which can have its own
border and background – it is used to group related widgets together in an application’s
layout.
Top level is a container widget which is displayed as a separate window.
Canvas is a widget for drawing graphics. In advanced usage, it can also be used to create
custom widgets – because we can draw anything we like inside it, and make it
interactive.
Text displays formatted text, which can be editable and can have embedded images.
A Button usually maps directly onto a user action – when the user clicks on a button,
something should happen.
class MyFirstGUI:
LABEL_TEXT = [
"This is our first GUI!",
"Actually, this is our second GUI.",
"We made it more interesting...",
"...by making this label interactive.",
"Go on, click on it again.",
]
def __init__(self, master):
self.master = master
master.title("A simple GUI")
self.label_index = 0
self.label_text = StringVar()
self.label_text.set(self.LABEL_TEXT[self.label_index])
self.label = Label(master, textvariable=self.label_text)
self.label.bind("<Button-1>", self.cycle_label_text)
self.label.pack()
self.greet_button = Button(master, text="Greet", command=self.greet)
self.greet_button.pack()
self.close_button = Button(master, text="Close", command=master.quit)
self.close_button.pack()
def greet(self):
print("Greetings!")
def cycle_label_text(self, event):
self.label_index += 1
self.label_index %= len(self.LABEL_TEXT) # wrap around
self.label_text.set(self.LABEL_TEXT[self.label_index])
root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()
Exercise:
1. Implement Tkinter in Python.
2. Design GUI for any application.
3. Implement custom events.
Review Question:
1. What is Tkinter and how it is used in Python?
2. Explain different components used in GUI programming.
3. What is custom events? Explain with an example.