0% found this document useful (0 votes)
61 views36 pages

PP Lab Manual

Uploaded by

Kiran Mudaliyar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views36 pages

PP Lab Manual

Uploaded by

Kiran Mudaliyar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Control Structure

Practical No:________ Date:___________

Aim: Develop Programs to understand the control structure of python

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:

Python programming language provides following types of loops to handle looping


requirements.

Loop Type Description


while loop Repeats a statement or group of statements while a given condition is
TRUE. It tests the condition before executing the loop body.
For loop Executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable.
nested loops You can use one or more loop inside any another while, for or do…
while loop.

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:

Gandhinagar Institute of Technology 2180711 Python Programming


The count is: 0
The count is: 1
The count is: 2
Good bye!
For Loop
It has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax
for iterating_var in sequence:
statements(s)

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']

for fruit in fruits: # Second Example


print 'Current fruit :', fruit

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.

Gandhinagar Institute of Technology 2180711 Python Programming


Break Statement
It terminates the current loop and resumes execution at the next statement, just like the
traditional break statement in C. The most common use for break is when some external
condition is triggered requiring a hasty exit from a loop. The break statement can be used in
both while and for loops. If you are using nested loops, the break statement stops the execution
of the innermost loop and start executing the next line of code after the block.

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

Gandhinagar Institute of Technology 2180711 Python Programming


Example
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter
When the above code is executed, it produces following result:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n

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?

Gandhinagar Institute of Technology 2180711 Python Programming


Python- Variable Types

Practical No: ________ Date: ___________


Aim: Develop Programs to learn different types of structures (list, dictionary and tuples) 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.

Gandhinagar Institute of Technology 2180711 Python Programming


The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot
be updated. Tuples can be thought of as read only lists.
Example
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints complete list
print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists

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?

Gandhinagar Institute of Technology 2180711 Python Programming


Python- Functions, Recursion and List

Practical No: ________ Date: ___________


Aim: Develop Programs to learn concepts of functions scoping, recursion and list mutability.

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

Gandhinagar Institute of Technology 2180711 Python Programming


Now we come to implement the factorial in Python. It's as easy and elegant as the mathematical
definition.
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
We can track how the function works by adding two print() functions to the previous function
definition:
def factorial(n):
print("factorial has been called with n = " + str(n))
if n == 1:
return 1
else:
res = n * factorial(n-1)
print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
return res
print(factorial(5))

Let's have a look at an iterative version of the factorial function.


def iterative_factorial(n):
result = 1
for i in range(2,n+1):
result *= i
return result
Mutability Common Types
The following are some immutable objects:
int
float
decimal
complex
bool
string
tuple
range
frozenset
bytes
The following are some mutable objects:
list
dict
set
bytearray
user-defined classes (unless specifically made immutable)

Syntax for declaring a list


Square brackets are used to denote a list object. Here's an empty list:
mylist = []
And here's a list with just a single member:
mylist = ['hello']
Lists can contain multiple objects. When the members of a list are written out in code, commas
are used to separate each member.

Gandhinagar Institute of Technology 2180711 Python Programming


Here's a very simple list of 2 string objects:
mylist = ["hello", "world"]
Lists can contain any other kind of object, including other lists. You can ignore the usual
Python indentation rules when declaring a long list; note that in the list below, the list inside
the main list counts as a single member:

>>> mylist = ["hello", "world", 1, 2, 9999, "pizza",


... 42, ["this", "is", "a", "sub list"], -100]
>>> len(mylist)
9
>>> mylist = ['a', 'b', 'c', 42]
>>> for x in mylist:
... print("Hello", x)
Hello a
Hello b
Hello c
Hello 42
Access a list's members by index
The members of a list are indexed with integers. Lists are zero-indexed, which means that the
first member of a list is available at the index value of 0.
To access a list's members, use square brackets immediately following the list, with the desired
index inside the brackets:
>>> mylist = [1, 2, 3]
>>> mylist[0]
1
>>> mylist[2]
3
>>> [4, 5, 6][1]
5

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?

Gandhinagar Institute of Technology 2180711 Python Programming


[This page intentionally left blank]

Gandhinagar Institute of Technology 2180711 Python Programming


Exception handling and assertions

Practical No: ________ Date: ___________

Aim: Develop Programs to understand working of exception handling and assertions.

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.

 Assertions − this would be covered in Assertions in Pythontutorial.

List of Standard Exceptions

Sr. No. Exception Name & Description

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

Gandhinagar Institute of Technology 2180711 Python Programming


Raised when an import statement fails.
13 KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing Ctrl+c.
14 LookupError
Base class for all lookup errors.
15 IndexError
Raised when an index is not found in a sequence.
16 KeyError
Raised when the specified key is not found in the dictionary.
17 NameError
Raised when an identifier is not found in the local or global namespace.
18 UnboundLocalError
Raised when trying to access a local variable in a function or method but no value has been
assigned to it.
19 EnvironmentError
Base class for all exceptions that occur outside the Python environment.
20 IOError
Raised when an input/ output operation fails, such as the print statement or the open()
function when trying to open a file that does not exist.
21 IOError
Raised for operating system-related errors.
22 SyntaxError
Raised when there is an error in Python syntax.
23 IndentationError
Raised when indentation is not specified properly.
24 SystemError
Raised when the interpreter finds an internal problem, but when this error is encountered
the Python interpreter does not exit.
25 SystemExit
Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the
code, causes the interpreter to exit.
26 TypeError
Raised when an operation or function is attempted that is invalid for the specified data type.
27 ValueError
Raised when the built-in function for a data type has the valid type of arguments.
28 RuntimeError
Raised when a generated error does not fall into any category.
29 NotImplementedError
Raised when an abstract method that needs to be implemented in an inherited class is not
actually implemented.

Gandhinagar Institute of Technology 2180711 Python Programming


What is Exception?
An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions. In general, when a Python script encounters a
situation that it cannot cope with, it raises an exception. An exception is a Python object that
represents an error.
When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits.
Handling an exception
If you have some suspicious code that may raise an exception, you can defend your program
by placing the suspicious code in a try: block. After the try: block, include
an except: statement, followed by a block of code which handles the problem as elegantly as
possible.
Syntax
Here is simple syntax of try....except...else blocks −
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.

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

fh.write("This is my test file for exception handling!!")

except IOError:

print "Error: can\'t find file or read data"

else:

print "Written content in the file successfully"

fh.close()

Gandhinagar Institute of Technology 2180711 Python Programming


This produces the following result −

Written content in the file successfully

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

fh.write("This is my test file for exception handling!!")

except IOError:

print "Error: can\'t find file or read data"

else:

print "Written content in the file successfully"

This produces the following result −

Error: can't find file or read data

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.

Gandhinagar Institute of Technology 2180711 Python Programming


Data Structure Algorithm

Practical No: ________ Date: ___________


Aim: Develop Programs for data structure algorithm using python- searching, sorting and hash
table.

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.

Gandhinagar Institute of Technology 2180711 Python Programming


Item Hash Value

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.

Item Remainder Mid-Square

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

Gandhinagar Institute of Technology 2180711 Python Programming


able to benefit from having a sorted list (recall the final anagram example and the binary
search).
There are many, many sorting algorithms that have been developed and analyzed. This suggests
that sorting is an important area of study in computer science. Sorting a large number of items
can take a substantial amount of computing resources. Like searching, the efficiency of a
sorting algorithm is related to the number of items being processed. For small collections, a
complex sorting method may be more trouble than it is worth. The overhead may be too high.
On the other hand, for larger collections, we want to take advantage of as many improvements
as possible. In this section we will discuss several sorting techniques and compare them with
respect to their running time.
 The Bubble Sort
 The Selection Sort
 The Insertion Sort
 The Shell Sort
 The Merge Sort
 The Quick Sort

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?

Gandhinagar Institute of Technology 2180711 Python Programming


[This page intentionally left blank]

Gandhinagar Institute of Technology 2180711 Python Programming


Regular Expressions

Practical No: ________ Date: ___________


Aim: Develop Program to learn regular expressions using python.

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.

The match Function


This function attempts to match RE pattern to string with optional flags.

Here is the syntax for this function −


re.match(pattern, string, flags=0)

Here is the description of the parameters −

Sr.No. Parameter & Description

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.

The re.match function returns a match object on success, None on failure. We


usegroup(num) or groups() function of match object to get matched expression.

Sr.No. Match Object Method & Description

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

line = "Cats are smarter than dogs"

Gandhinagar Institute of Technology 2180711 Python Programming


matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)

if matchObj:

print "matchObj.group() : ", matchObj.group()

print "matchObj.group(1) : ", matchObj.group(1)

print "matchObj.group(2) : ", matchObj.group(2)

else:

print "No match!!"

When the above code is executed, it produces following result −

matchObj.group() : Cats are smarter than dogs


matchObj.group(1) : Cats
matchObj.group(2) : smarter
The search Function
This function searches for first occurrence of RE pattern within string with optional flags.
Here is the syntax for this function −

re.search(pattern, string, flags=0)


Here is the description of the parameters −

Sr.No. Parameter & Description

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.

The re.search function returns a match object on success, none on failure. We


use group(num) or groups() function of match object to get matched expression.

Sr.No. Match Object Methods & Description

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)

Gandhinagar Institute of Technology 2180711 Python Programming


Example

#!/usr/bin/python

import re

line = "Cats are smarter than dogs";

searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)

if searchObj:

print "searchObj.group() : ", searchObj.group()

print "searchObj.group(1) : ", searchObj.group(1)

print "searchObj.group(2) : ", searchObj.group(2)

else:

print "Nothing found!!"

When the above code is executed, it produces following result −


searchObj.group() : Cats are smarter than dogs
searchObj.group(1) : Cats
searchObj.group(2) : smarter
Matching Versus Searching
Python offers two different primitive operations based on regular expressions: match checks
for a match only at the beginning of the string, while searchchecks for a match anywhere in
the string (this is what Perl does by default).
Example

#!/usr/bin/python

import re

line = "Cats are smarter than dogs";

matchObj = re.match( r'dogs', line, re.M|re.I)

if matchObj:

print "match --> matchObj.group() : ", matchObj.group()

else:

print "No match!!"

searchObj = re.search( r'dogs', line, re.M|re.I)

if searchObj:

print "search --> searchObj.group() : ", searchObj.group()

else:

Gandhinagar Institute of Technology 2180711 Python Programming


print "Nothing found!!"
When the above code is executed, it produces the following result −
No match!!
search --> matchObj.group() : dogs
Search and Replace
One of the most important re methods that use regular expressions is sub.
Syntax
re.sub(pattern, repl, string, max=0)
This method replaces all occurrences of the RE pattern in string with repl, substituting all
occurrences unless max provided. This method returns modified string.
Example

#!/usr/bin/python

import re

phone = "2004-959-559 # This is Phone Number"

# Delete Python-style comments

num = re.sub(r'#.*$', "", phone)

print "Phone Num : ", num

# Remove anything other than digits

num = re.sub(r'\D', "", phone)

print "Phone Num : ", num


When the above code is executed, it produces the following result −
Phone Num : 2004-959-559
Phone Num : 2004959559

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?

Gandhinagar Institute of Technology 2180711 Python Programming


Multithreading

Practical No: ________ Date: ___________


Aim: Develop chat room application multithreading.

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.

Server Side Script


The server side script will attempt to establish a socket and bind it to an IP address and port
specified by the user (windows users might have to make an exception for the specified port
number in their firewall settings, or can rather use a port that is already open). The script will
then stay open and receive connection requests, and will append respective socket objects to
a list to keep track of active connections.

Client Side Script


The client side script will simply attempt to access the server socket created at the specified
IP address and port. Once it connects, it will continuously check as to whether the input comes
from the server or from the client, and accordingly redirects output. If the input is from the
server, it displays the message on the terminal. If the input is from the user, it sends the
message that the users enters to the server for it to be broadcasted to other users.
Exercise:
1. Write a program to demonstrate Client-Server chat application.

Review Question:
1. Explain what Client Side Script & Server side Script?
2. Want is the usage of multithreading?
.

Gandhinagar Institute of Technology 2180711 Python Programming


[This page intentionally left blank]

Gandhinagar Institute of Technology 2180711 Python Programming


GRAPHS

Practical No: ________ Date: ___________


Aim: Learn to plot different types of graphs using PyPlot

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

Gandhinagar Institute of Technology 2180711 Python Programming


is used to restore the figure to its original appearance after you are done playing with pan and
zoom. It is possible to produce multiple figures and to write them to files. These files can
have any name you like, but they will all have the file extension .png. The file extension .png
indicates that the file is in the Portable Networks Graphics format. This is a public domain
standard for representing images.
The code
pylab.figure(1) #create figure 1
pylab.plot([1,2,3,4], [1,2,3,4]) #draw on figure 1
pylab.figure(2) #create figure 2
pylab.plot([1,4,2,3], [5,6,7,8]) #draw on figure 2
pylab.savefig('Figure-Addie') #save figure 2

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

Gandhinagar Institute of Technology 2180711 Python Programming


years = 20
values = []
for i in range(years + 1):
values.append(principal)
principal += principal*interestRate
pylab.plot(values, linewidth = 30)
pylab.title('5% Growth, Compounded Annually',
fontsize = 'xx-large')
pylab.xlabel('Years of Compounding', fontsize = 'x-small')
pylab.ylabel('Value of Principal ($)')
It is also possible to change the default values, which are known as “rc settings.” (The name
“rc” is derived from the .rc file extension used for runtime configuration files in Unix.) These
values are stored in a dictionary-like variable that can be accessed via the name pylab.rcParams.
So, for example, you can set the default line width to 6 points61 by executing the code:
pylab.rcParams['lines.linewidth'] = 6.
The default values used in most of the examples in this book were set with the code #set line
width
pylab.rcParams['lines.linewidth'] = 4
#set font size for titles
pylab.rcParams['axes.titlesize'] = 20
#set font size for labels on axes
pylab.rcParams['axes.labelsize'] = 20
#set size of numbers on x-axis
pylab.rcParams['xtick.labelsize'] = 16
#set size of numbers on y-axis
pylab.rcParams['ytick.labelsize'] = 16
#set size of ticks on x-axis
pylab.rcParams['xtick.major.size'] = 7
#set size of ticks on y-axis
pylab.rcParams['ytick.major.size'] = 7
#set size of markers
pylab.rcParams['lines.markersize'] = 10
If you are viewing plots on a color display, you will have little reason to customize these
settings. We customized the settings we used so that it would be easier to read the plots when
we shrank them and converted them to black and white.

Gandhinagar Institute of Technology 2180711 Python Programming


Exercise:
1. Plot a graph using Pyplot.
2. Plot difference graph using Pyplot.
3. Plot a variable graph using Pyplot.

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.

Gandhinagar Institute of Technology 2180711 Python Programming


CLASSICAL CIPHER

Practical No: ________ Date: ___________


Aim: Implement classical cipher using python

Theory

The Reverse Cipher


The reverse cipher encrypts a message by printing it in reverse order. So “Hello world!”
encrypts to “!dlrow olleH”. To decrypt, you simply reverse the reversed message to get the
original message. The encryption and decryption steps are the same.
The reverse cipher is a very weak cipher. Just by looking at its cipher text you can figure out it
is just in reverse order. .syas ti tahw tuo erugif llits ylbaborp nac uoy ,detpyrcne si siht hguoht
neve ,elpmaxe roF
But the code for the reverse cipher program is easy to explain, so we’ll use it as our first
encryption program.

Source Code of the Reverse Cipher Program


# Reverse Cipher
# http://inventwithpython.com/hacking (BSD Licensed)
message = 'Three can keep a secret, if two of them are dead.'
translated = ''
i = len(message) - 1
while i >= 0:
translated = translated + message[i]
i=i-1
print(translated)
The ceaser cipher

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.

Encrypting with the Transposition Cipher


Instead of replacing characters with other characters, the transposition cipher jumbles up the
message’s symbols into an order that makes the original message unreadable. Before we start
writing code, let’s encrypt the message “Common sense is not so common.” with pencil and
paper. Including the spaces and punctuation, this message has 30 characters. We will use the
number 8 for the key.
The first step is to draw out a number of boxes equal to the key. We will draw 8 boxes since
our key for this example is 8:

Gandhinagar Institute of Technology 2180711 Python Programming


The second step is to start writing the message you want to encrypt into the boxes, with one
character for each box. Remember that spaces are a character (this book marks the boxes with
(s) to indicate a space so it doesn’t look like an empty box).

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.

A Transposition Cipher Encryption Program


Encrypting with paper and pencil involves a lot of work and it’s easy to make mistakes. Let’s
look at a program that can implement transposition cipher encryption (a decryption program
will be demonstrated later in this chapter).

Decrypting with the Transposition Cipher on Paper


Let’s pretend we send the ciphertext “Cenoonommstmme oo snnio. s s c” to a friend (and she
already knows that the secret key is 8). The first step for her to decrypt the ciphertext is to
calculate how many boxes she needs to draw. To find this amount, divide the length of the
ciphertext message by the key and round up. The length of our ciphertext is 30 characters
(exactly the same as the plaintext) and the key is 8. So calculate 30 divided by 8 to get 3.75.
3.75 rounds up to 4. This means we want to draw a grid of boxes with 4 columns (the number
we just calculated) and 8 rows (the key). It will look like this:

(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.)

Gandhinagar Institute of Technology 2180711 Python Programming


The second thing we need to calculate is how many boxes on the rightmost column to shade
in. Take the total number of boxes (32) and subtract the length of the ciphertext (30). 32 – 30
= 2, so shade in the bottom 2 boxes on the rightmost column:

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.

Gandhinagar Institute of Technology 2180711 Python Programming


[This page intentionally left blank]

Gandhinagar Institute of Technology 2180711 Python Programming


Turtle

Practical No: ________ Date: __________


Aim: Draw graphics using Turtle.
Theory
Turtle graphics is a popular way for introducing programming to kids. It was part of the original
Logo programming language developed by Wally Feurzig and Seymour Papert in 1966.
Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an import turtle, give it the
command turtle.forward(15), and it moves (on-screen!) 15 pixels in the direction it is facing,
drawing a line as it moves. Give it the command turtle.right(25), and it rotates in-place 25
degrees clockwise.
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-
oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python
installed with Tk support.
The object-oriented interface uses essentially two+two classes:
The TurtleScreen class defines graphics windows as a playground for the drawing turtles. Its
constructor needs a Tkinter.Canvas or a ScrolledCanvas as argument. It should be used when
turtle is used as part of some application.
The function Screen() returns a singleton object of a TurtleScreen subclass. This function
should be used when turtle is used as a standalone tool for doing graphics. As a singleton object,
inheriting from its class is not possible.
All methods of TurtleScreen/Screen also exist as functions, i.e. as part of the procedure-
oriented interface.
RawTurtle (alias: RawPen) defines Turtle objects which draw on a TurtleScreen. Its
constructor needs a Canvas, ScrolledCanvas or TurtleScreen as argument, so the RawTurtle
objects know where to draw.
Derived from RawTurtle is the subclass Turtle (alias: Pen), which draws on “the” Screen -
instance which is automatically created, if not already present.
All methods of RawTurtle/Turtle also exist as functions, i.e. part of the procedure-oriented
interface.

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:

Gandhinagar Institute of Technology 2180711 Python Programming


Name Description Features

Bytedesign complex classical turtlegraphics pattern tracer(), delay, update()

graphs Verhulst dynamics, shows that


computer’s computations can generate
Chaos world coordinates
results sometimes against the common sense
expectations

analog clock showing time of your turtles as clock’s


Clock
computer hands, ontimer

colormixer experiment with r, g, b ondrag()

fractalcurves Hilbert & Koch curves Recursion

lindenmayer ethnomathematics (indian kolams) L-System

Rectangular Turtles as
minimal_hanoi Towers of Hanoi Hanoi discs (shape,
shapesize)

Paint super minimalistic drawing program onclick()

turtle: appearance and


peace Elementary
animation

penrose aperiodic tiling with kites and darts stamp()

compound
planet_and_moon simulation of gravitational system
shapes, Vec2D

a (graphical) breadth first tree (using


Tree clone()
generators)

a pattern from the wikipedia article on turtle


Wikipedia clone(), undo()
graphics

Yinyang another elementary example circle()


Exercise:
1. Implement Special turtle method with suitable example.
2. Implement any of the demo scripts with suitable example.
3. Implement turtle’s different state with suitable example.

Review Question:
1. Explain different methods of turtle graphics.
2. List turtle’s state different methods.

Gandhinagar Institute of Technology 2180711 Python Programming


Tkinter

Practical No: ________ Date: ___________


Aim: Develop Program to learn GUI programming using Tkinter.
Theory
Tkinter provides us with a variety of common GUI elements which we can use to build our
interface – such as buttons, menus and various kinds of entry fields and display areas. We call
these elements widgets. We are going to construct a tree of widgets for our GUI – each widget
will have a parent widget, all the way up to the root window of our application. For example,
a button or a text field needs to be inside some kind of containing window.
The widget classes provide us with a lot of default functionality. They have methods for
configuring the GUI’s appearance – for example, arranging the elements according to some
kind of layout – and for handling various kinds of user-driven events. Once we have
constructed the backbone of our GUI, we will need to customize it by integrating it with our
internal application class.
Our first GUI will be a window with a label and two buttons:
from tkinter import Tk, Label, Button
class MyFirstGUI:
def __init__(self, master):
self.master = master
master.title("A simple GUI")
self.label = Label(master, text="This is our first GUI!")
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!")
root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()

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.

Gandhinagar Institute of Technology 2180711 Python Programming


 A Label is a simple widget which displays a short piece of text or an image, but usually
isn’t interactive.
 A Message is similar to a Label, but is designed for longer bodies of text which need
to be wrapped.
 A Scrollbar allows the user to scroll through content which is too large to be visible all
at once.
 Checkbutton, Radiobutton, Listbox, Entry and Scale are different kinds of input
widgets – they allow the user to enter information into the program.
 Menu and Menubutton are used to create pull-down menus.

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.

Gandhinagar Institute of Technology 2180711 Python Programming

You might also like