S R SW TI: College of Engineering

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 39

SɅRɅSWɅTI College

Collegeofof
Department of Computer Engineering Engineering
Engineering
Saraswati College of Engineering, Kharghar

Vision:

To become center of excellence in Engineering education and research.

Mission:

To educate students to become quality technocrats for taking up challenges in all facets of life.

Department of Computer Engineering

Vision:

To imprint knowledge to our students to excel in engineering culture and research and nurture
them to become ethically rich professionals.

Mission:

To provide simulating learning environment with a technological orientation to maximize


individual potential.

SARASWATI EDUCATION SOCIETY’S


SARASWATI COLLEGE OF ENGINEERING,

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
NAVI MUMBAI, KHARGHAR.

COMPUTER ENGINEERING DEPARTMENT

Programme Outcomes (PO)

1. An ability to apply knowledge of mathematics, science and engineering.


2. Ability to apply the engineering knowledge in all domains, viz., health care, banking
and Finance, other professions such as medical, law, etc.
3. An ability to design and conduct experiments as well as to analyze and interpret data.
4. Ability to analyze the problem, subdivide into smaller tasks with well-defined interface
for interaction among components, and complete within the specified time frame and
financial constraints,
5. An ability to design a system, component or process to meet the desired needs within
realistic constraints such as economic, environmental, social, political and Ethical
ability,
6. Ability to design, implement, and evaluate secure hardware and/or software systems
with assured quality and efficiency,
7. Ability to communicate effectively the engineering solution to customers/users or
peers,
8. An understanding of professional and ethical responsibilities,
9. Ability to understand contemporary issues and to get engaged in lifelong learning by
independently and continually expanding knowledge and abilities,
10. An ability to function in multidisciplinary teams,
11. An ability to identify, formulate and solve engineering problems.

SARASWATI EDUCATION SOCIETY’S


SARASWATI COLLEGE OF ENGINEERING,
NAVI MUMBAI, KHARGHAR

COMPUTER ENGINEERING DEPARTMENT

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering

Program Educational Objectives (PEO)

1. To prepare the candidate for a successful career in the industry and make him
acquainted with the latest software and hardware,
2. To enable student to work productively as computer engineers, including supportive
teamwork and leadership roles on multidisciplinary teams,
3. Graduates are prepared to be responsible computing professionals in their own area of
interest,
4. To provide the candidate with a sound foundation in mathematics, software
technologies, database technologies, networking, hardware and to prepare them for post
graduate studies and research programs,
5. To promote the awareness of lifelong learning among students and to introduce them to
professional ethics and codes of professional practice,
6. To demonstrate effective communication skills in oral, written and electronic media.

Lab Code Lab Name Credit

CSL405 Open Source Technology Lab 2

Course Outcomes:

1. To understand basic concepts in python and perl.

2. To explore contents of files, directories and text processing with python

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
3. To develop program for data structure using built in functions in python.

4. To explore django web framework for developing python based web application.

5. To understand file handling and database handling using perl.

6. To explore basics of two way communication between client and server using python and perl

Prerequisites: Knowledge of some programming language like C, Java

Content:

Sr. No Module Name Detailed Content

1 Python basics Data types in python ,Operators in python, Input and Output, Control

statement, Arrays in python, String and Character in python, Functions,

List and Tuples, Dictionaries Exception, Introduction to OOP, Classes ,

Objects , Interfaces, Inheritance

2 Advanced Python Files in Python, Directories, Building Modules, Packages, Text

Processing, Regular expression in python.

3 Data Structure in Python Link List, Stack, Queues, Dequeues

4 Python Integration Graphical User interface ,Networking in Python , Python database

Primer connectivity, Introduction to Django

5 Basics of Perl Perl Overview, Variables, Control Statements, Subroutines, Objects,

Packages and Modules

6 Perl advanced Working with Files, Data manipulation, Database Systems, Networking

Text Books

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
1. Core Python Programming, Dr. R. Nageswara Rao, Dreamtech Press

2. Beginning Python: Using Python 2.6 and Python 3.1. James Payne, Wrox publication

3. Perl: The Complete Reference. Second Edition. Martin C. Brown, McGraw-Hill

4. Introduction to computing and problem solving using python , E


Balagurusamy,McGraw Hill Education

Reference Book

1. Perl Black Book, 2nd Edition: Steven Holzner,Dreamtech Press

2. Learn Python the Hard Way: (3rd Edition) (Zed Shaw's Hard Way Series)

3. Python Projects , Laura Cassell,Alan Gauld,wrox publication

Digital Material:

1. "The Python Tutorial", http://docs.python.org/release/3.0.1/tutorial/

2. Beginning Perl, https://www.perl.org/books/beginning-perl/

3. http://spoken-tutorial.org

4. www.staredusolutions.org

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
SARASWATI COLLEGE OF ENGINEERING
COMPUTER ENGINEERING DEPARTMENT

Subject: Open Source Technology Lab (OSTL) Class / Sem: SE/IV

Name of the Laboratory: Mulimedia Lab Year: 2018-2019

LIST OF EXPERIMENTS

Sr no. Experiment
1 Program to swap two numbers and check if first number is positive or
negative or zero.

2 Program to check if number and string is palindrome and find factorial of


input number.

3 Menu driven program to demonstrate use of list in python.

A. Put even and odd elements into two different lists.

B. Merge and sort two lists.

C. Update first element with x value and delete middle element of list.

D. Find max and min element from list.

E. Add n names into the existing number list and check if word python is
present in list.

4 Menu driven program to demonstrate use of tuples in python.

A. Add and show N student roll number, name and 3 subject marks in a list
of tuples.

B. Display student roll number and marks whose name is python.

C. Demonstrate nested tuple and sort nested tuple by name.

5 Menu driven program to demonstrate use of set in python

A. Accept two strings from user

B. Display common letters in two input strings(set intersection)

C. Display letters which are in the first string but not in the second.(set
difference)

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
D. Display set of all letters of both the strings.(set union)

E. Displays letters which are in the two strings but not in both.(symmetric
difference)

6 Menu driven program to demonstrate use of dictionary in python

A. Create key/value pair dictionary.

B. Update/concatenate and delete item of existing dictionary.

C. Find a key and print its value.

D. Map two list into dictionary.


7 Design an employee class using python for reading and displaying the
employee information.
8 Program to demonstrate single and multiple inheritance in python (with
method overloading and overriding)

9 Exception handling

A. Write a program to demonstrate exception handling using try, multiple


exception and finally.

B. Write a python program to create user defined exception.

10 Exploring files and directories.

A. Python program to read the content of file and write in another


file.

B. Program to append data to existing file and then display entire file.

C. Program to count number of lines, words and characters in a file.

D. Program to display file available in current directory.

11 Create a package and module for data structure :stack and queues.
12 Creation of simple socket for basic info exchange between server and client.

13 A. Perl script to find a factorial of a number using for and until loop if the
number is even number.

B. Demonstrate use of Array.

C. Demonstrate use of Hash.

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
14 Design a class person and create its objects in perl.

15 A. Program to demonstrate file handling in perl.

B. Use of regular expression for text processing in perl.

H/W Requirement P-IV and above, Ram 128 MB, Printer, Internet Connection

S/W Requirement Python IDLE

Mrs. Pradnya Patil Deepa Parasar


Subject I/C H.O.D.

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 1
Aim: Program to swap two numbers and check if first number is positive or negative or

zero

Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE

Theory: Python is a general-purpose interpreted, interactive, object-oriented, and high- level


programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl,
Python source code is also available under the GNU General Public License (GPL).

There are 3 ways of executing a Python program

1. Using Python’s command line window.

2. Using Python’s IDLE graphics window.

3. Directly from System prompt.

The first two are called interactive modes where we can type the program one line at a time
and the complier executes it immediately. The last one is called non-interactive mode where we
ask complier to execute our program after typing the entire program. Programmers can store
Python script source code in a file with the ’.py’ extension, and use the interpreter to execute
the contents of the file. To execute the script by the interpreter, you have to tell the interpreter
the name of the file. Decision making is required when we want to execute a code only if a
certain condition is satisfied. The if…elif…else statement is used in Python for decision
making. Syntax for if statement as follows:

1. if expression:

//execute your code

2. if expression:

//execute your code

else:

//execute your code

3. if expression:

//execute your code

elif expression:

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
//execute your code

else:

//execute your code

Conclusion: We have studied how to run python program and swapping of two number,
control statement if else for find the given number is positive, negative or zero .

By Student -______________________________________________________

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 2
Aim: Menu driven program to check if number and string is palindrome and find factorial of

input number.

Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE.

Theory: Functions in python.

The four steps to defining a function in Python are the following:

1. Use the keyword def to declare the function and follow this up with the function name.

2. Add arguments to the function: they should be within the parentheses of the function. End
your line with a colon.

3. Add statements that the functions should execute.

4. End your function with a return statement if the function should output something. Without
the return statement, your function will return an object None.

5. docstring is short for documentation string. It is used to explain in brief, what a function
does.

Syntax for functions in python:

def function_name(parameters):

"""docstring"""

statement(s)

A palindrome is a string which is same read forward or backwards. For example: "dad" is the
same in forward or reverse direction. Another example is "aibohphobia" which literally means,
an irritable fear of palindromes. The factorial of a number is the product of all the integers
from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Factorial is not defined for negative numbers and the factorial of zero is one, 0! = 1.

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Conclusion: We have studied how to write functions in python program to find palindrome
and factorial of number.

By Student -______________________________________________________

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 3
Aim: Write a Menu driven program to demonstrate use of list in python.

A. Put even and odd elements into two different lists.

B. Merge and sort two lists.

C. Update first element with x value and delete middle element of list.

D. Find max and min element from list.

E. Add n names into the existing number list and check if word python is present in list.

Hardware and Software Requirement: P-IV and above, Ram 128 MB, python IDLE.

Theory: Lists are positionally ordered collections of arbitrarily typed objects, and they have no
fixed size and they are mutable. Lists are contained in square brackets []. Lists can contain
numbers, strings, nested sublists, or nothing

Examples: L1 = [0,1,2,3],

L2 = ['zero', 'one'],

L3 = [0,1,[2,3],'three',['four,one']],

L4 = [].

List indexing works just like string indexing. Lists are mutable: individual elements can be
reassigned in place. Moreover, they can grow and shrink in place.

Example:

>>> L1 = [0,1,2,3]

>>> L1[0] = 4

>>> L1[0]

Basic List Operations Lists respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new list, not a string. Some of
basic operations of list are as follows.

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Python includes the following list functions –

Sr No Function Description

1 cmp(list1, list2) Compares elements of both


lists.

2 len(list) Gives the total length of the


list.

3 max(list) Returns item from the list


with max value.

4 min(list) Returns item from the list


with min value.

5 list(seq) Converts a tuple into list.

Python includes following list methods:

Sr.No Methods Description

1 list.append(obj) Appends object obj to list 2

2 list.count(obj) Returns count of how many


times obj occurs in list

3 list.extend(seq) Appends the contents of seq


to list

4 list.index(obj) Returns the lowest index in


list that obj appears

5 list.insert(index, obj) Inserts object obj into list at


offset index

6 list.pop(obj=list[-1]) Removes and returns last


object or obj from list

7 list.remove(obj) Removes object obj from list

8 list.reverse() Reverses objects of list in


place

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Conclusion: Hence from above experiment student can understand that basic concept of list
and list related various operation that create the list ,update the list, merge the list etc.

By Student -______________________________________________________

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 4
Aim: Menu driven program to demonstrate use of tuples in python.

A. Add and show N student roll number, name and 3 subject marks in a list of tuples.

B. Display student roll number and marks whose name is python.

C. Demonstrate nested tuple and sort nested tuple by name.

Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE.

Theory: A tuple is a sequence of immutable Python objects. Tuples are sequences, just like
lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and
tuples use parentheses, whereas lists use square brackets. Creating a tuple is as simple as
putting different comma-separated values. Optionally you can put these comma-separated
values between parentheses also. For example

tup1 = ('physics', 'chemistry', 1997, 2000);

tup2 = (1, 2, 3, 4, 5 );

tup3 = "a", "b", "c", "d";

Advantages of Tuple over List

However, there are certain advantages of implementing a tuple over a list. Below listed are
some of the main advantages:

 We generally use tuple for heterogeneous (different) datatypes and list for
homogeneous (similar) datatypes.

 Since tuple are immutable, iterating through tuple is faster than with list. So there is a
slight performance boost.

 Tuples that contain immutable elements can be used as key for a dictionary. With list,
this is not possible.

 If you have data that doesn't change, implementing it as tuple will guarantee that it
remains write-protected.

1. Creating a Tuple

A tuple is created by placing all the items (elements) inside a parentheses (), separated by
comma. The parentheses are optional but is a good practice to write it. A tuple can have any
number of items and they may be of different types (integer, float, list, string etc.).

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
2. Accessing Elements in a Tuple There are various ways in which we can access the
elements of a tuple.

a. Indexing

We can use the index operator [] to access an item in a tuple where the index starts from 0.
So, a tuple having 6 elements will have index from 0 to 5. Trying to access an element
other that (6, 7,...) will raise an IndexError. The index must be an integer, so we cannot use
float or other types. This will result into TypeError.

b. Negative Indexing

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2
to the second last item and so on.

c. Changing a Tuple

Unlike lists, tuples are immutable. This means that elements of a tuple cannot be changed
once it has been assigned. But, if the element is itself a mutable datatype like list, its nested
items can be changed.
d. Python Tuple Methods

Methods that add items or remove items are not available with tuple. Only the following two
methods are available.

Method Description

count(x) Return the number of items


that is equal to x

index(x) Return index of first item


that is equal to x

Conclusion: Hence from this experiment we learned the various functions of tuples like delete,
modify or insert elements of tuples since tuple are immutable, so for that how to create a new
tuple and store the updated elements in it.

By Student -______________________________________________________

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 5
Aim: Write a menu driven program to demonstrate use of set in python

A. Accept two strings from user

B. Display common letters in two input strings (set intersection)

C. Display letters which are in the first string but not in the second (set difference)

D. Display set of all letters of both the strings (set union)

E. Displays letters which are in the two strings but not in both (symmetric difference)

Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE.

Theory: A Set is an unordered collection data type that is iterable, mutable and has no
duplicate elements. Python’s set class represents the mathematical notion of a set. The major
advantage of using a set, as opposed to a list, is that it has a highly optimized method for
checking whether a specific element is contained in the set. This is based on a data structure
known as a hash table.

Methods for Sets:

1. add(x) Method: Adds the item x to set if it is not already present in


the set.

2. union(s) Method: Returns a union of two set. Using the ‘|’ operator
between 2 sets is the same as writing set1.union(set2)

3. intersect(s) Method: Returns an intersection of two sets. The ‘&’


operator comes can also be used in this case.

4. difference(s) Method: Returns a set containing all the elements of


invoking set but not of the second set. We can use ‘-‘ operator
here.

5. clear() Method: Empties the whole set.

Conclusion: Hence from this experiment we learned the various operations of sets in python.

By Student -______________________________________________________

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 6
Aim: Menu driven program to demonstrate use of dictionary in python

A. Create key/value pair dictionary.

B. Update/concatenate and delete item of existing dictionary.

C. Find a key and print its value.

D. Map two lists into dictionary.

Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE.

Theory: Dictionary in python consists of keys and their values.

1. Create a Python Dictionary Here is an example of how we can create a dictionary in


Python :

>>> myDict = {"A":"Apple", "B":"Boy", "C":"Cat"}

In the above example: A dictionary is created. This dictionary contains three elements.
Each element constitutes of a key value pair. This dictionary can be accessed using the
variable myDict.

2. Access Dictionary Elements Once a dictionary is created, you can access it using the
variable to which it is assigned during creation. For example, in our case, the variable
myDict can be used to access the dictionary elements. Here is how this can be done :

>>> myDict["A"]

'Apple'

>>> myDict["B"]

'Boy'

>>> myDict["C"]

'Cat'

So you can see that using the variable myDict and Key as index, the value of
corresponding key can be accessed. For those who have C/C++ background, it’s more
like accessing the value kept at a particular index in an array. If you just type the name
of the variable myDict, all the key value pairs in the dictionary will be printed.

>>> myDict {'A': 'Apple', 'C': 'Cat', 'B': 'Boy'}

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Only dictionary keys can be used as indexes. This means that myDict[“A”] would
produce ‘Apple’ in output but myDict[“Apple”] cannot produce ‘A’ in the output.

>>> myDict["Apple"]

Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'Apple'
So we see that the python compiler complained about ‘Apple’ being used as index.

3. Update Dictionary Elements Just the way dictionary values are accessed using keys,
the values can also be modified using the dictionary keys. Here is an example to
modify python dictionary element:

>>> myDict["A"] = "Application"

>>> myDict["A"] 'Application'

>>> myDict

{'A': 'Application', 'C': 'Cat', 'B': 'Boy'}

You can see that in the example shown above, the value of key ‘A’ was changed from
‘Apple’ to ‘Application’ easily. This way we can easily conclude that there could not be
two keys with same name in a dictionary.

4. Delete Dictionary Elements Individual elements can be deleted easily from a


dictionary. Here is an example to remove an element from dictionary.

>>> myDict {'A': 'Application', 'C': 'Cat', 'B': 'Boy'}

>>> del myDict["A"]

>>> myDict

{'C': 'Cat', 'B': 'Boy'}

So you can see that by using ‘del’ an element can easily be deleted from the dictionary.

If you want to delete complete dictionary i.e all the elements in the dictionary then it
can be done using the clear() function. Here is an example :

>>> myDict {'C': 'Cat', 'B': 'Boy'}

>>> myDict.clear()

>>> myDict

{}

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
So you see that all the elements were deleted making the dictionary empty.

1. Dictionaries are Unordered

>>> myDict = {"A":"Apple", "B":"Boy", "C":"Cat"}

>>> myDict

{'A': 'Apple', 'C': 'Cat', 'B': 'Boy'}

You can observe that the order of elements while the dictionary was being created is
different from the order in which they are actually stored and displayed.

Even if you try to add other elements to python dictionary:

>>> myDict["D"] = "Dog"

>>> myDict

{'A': 'Apple', 'C': 'Cat', 'B': 'Boy', 'D': 'Dog'}

>>> myDict["E"] = "Elephant"

>>> myDict

{'A': 'Apple', 'C': 'Cat', 'B': 'Boy', 'E': 'Elephant', 'D': 'Dog'}

You’ll observe that it’s not necessary that elements will be stored in the same order in
which they were created.

2. Dictionary Keys are Case Sensitive. Same key name but with different case are
treated as different keys in python dictionaries. Here is an example :

>>> myDict["F"] = "Fan"

>>> myDict["f"] = "freeze"

>>> myDict

{'A': 'Apple', 'C': 'Cat', 'B': 'Boy', 'E': 'Elephant', 'D': 'Dog', 'F': 'Fan', 'f'’: ‘freeze '}

Conclusion: Hence from this experiment we learned the various operation of dictionary like
create, modify or insert elements of dictionary and how two lists can merge in the dictionary.

By Student -______________________________________________________

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 7
Aim: Design an employee class using python for reading and displaying the employee

information.

Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE

Theory:

Creating Classes:

The class statement creates a new class definition. The name of the class immediately follows
the keyword class followed by a colon as follows –

class ClassName:
'Optional class documentation string'
class_suite

 The class has a documentation string, which can be accessed via ClassName.__doc__.

 The class_suite consists of all the component statements defining class members, data
attributes and functions.

Creating Instance Objects:

To create instances of a class, you call the class using class name and pass in whatever
arguments its __init__ method accepts.

Accessing Attributes

You access the object's attributes using the dot operator with object.

Conclusion: Hence from this experiment we learned how to create classes and its objects in
python.

By Student -______________________________________________________

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 8
Aim: Program to demonstrate single and multiple inheritance in python (with method

overloading and overriding)

Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE3

Theory:

Inheritance means deriving properties from other classes.


Types of Inheritance:
1. Single Inheritance: A derived class with only one base class is called as Single Inheritance.

2. Multiple Inheritances: A derived class with several base classes is called Multiple

Inheritance.

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
3. Hierarchical Inheritance: More than one class may inherit the features of one class this
process is called as Hierarchical Inheritance.

4. Multilevel Inheritance: The mechanism of deriving a class from another derived class is

called Multilevel Inheritance.

5. Hybrid Inheritance: There could be situations where we need to apply one or more types
of inheritances to design a program this process is called Hybrid Inheritance.

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Method overloading: In Python you can define a method in such a way that there are multiple
ways to call it. Given a single method or function, we can specify the number of parameters
ourselves. Depending on the function definition, it can be called with zero, one, two or more
parameters. This is known as method overloading.

Example: class operation:

def abc(self, a=None):

if a is not None:

print ('first num is' + a)

else:

print ('no number assigned ')

obj = operation()

obj.abc ()

obj.abc('10')

Method overriding: Overriding is the ability of a class to change the implementation of a


method provided by one of its ancestors. In Python method overriding occurs simply defining
in the child class a method with the same name of a method in the parent class.

Example

class Parent(object):

def __init__(self):

self.value = 5

def get_value(self): ### overridden method

return self.value

class Child(Parent):

def get_value(self):

return self.value + 1

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering

Conclusion: From this experiment we studied how to write a class and use the concept of
inheritance to achieve the specified requirements.

By Student -______________________________________________________

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 9
Aim: Exception handling

A. Write a program to demonstrate exception handling using try, multiple exception and
finally.

B. Write a python program to create user defined exception.

Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE3

Theory:

Python provides two very important features to handle any unexpected error in your Python
programs and to add debugging capabilities in them:

a. Exception Handling

b. Assertions

List of Standard Exceptions –

Sr.No Exception Name Description

1 Exception Base class for all exceptions

2 StandardError Base class for all built-in exceptions except StopIteration and
SystemExit.

3 ArithmeticError Base class for all errors that occur for numeric calculation.

4 OverflowError Raised when a calculation exceeds maximum limit for a


numeric type.

5 NameError Raised when an identifier is not found in the local or global


namespace.

6 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.

7 TypeError Raised when an operation or function is attempted that is


invalid for the specified data type.

8 ValueError It is raised when the built-in function for a data type has the
valid type of arguments, but the arguments have invalid values
specified.

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering

Conclusion: From this experiment we studied how to use standard exceptions and create user
defined exceptions in python.

By Student -______________________________________________________

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 10
Aim: Exploring files and directories.

A. Python program to read the content of file and write in another file.

B. Program to append data to existing file and then display entire file.

C. Program to count number of lines, words and characters in a file.

D. Program to display file available in current directory.

Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE3

Theory:

Data is very important. Every organization depends on its data for continuing its business
operations. To store the data in computer we need files. There are certain advantages of storing
data in file:

a. to store huge amount of data When data is stored in a file, it is stored permanently.

b. It is possible to update the file data.

c. Files are highly useful.

In Python, there are two types of files. They are

1. Text File-: store the data in the form of characters

2. Binary File-: store the entire data in the form of bytes.

It is very important to know how to create files, store data in the files and retrieve the data
from the files in python. To do any operations on files, first of all we should open the files.

Opening a File in order to open a file for writing or use in Python, you must rely on the built-in
open () function.

As explained above, open ( ) will return a file object, so it is most commonly used with two
arguments. An argument is nothing more than a value that has been provided to a function,
which is relayed when you call it. So, for instance, if we declare the name of a file as “Test
File,” that name would be considered an argument. The syntax to open a file object in Python
is:

file_object = open(“filename”, “mode”) where file_object is the variable to add the file object.
Mode Including a mode argument is optional because a default value of ‘r’ will be assumed if
it is omitted. The ‘r’ value stands for read mode, which is just one of many. The modes are:

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
‘r’ – Read mode which is used when the file is only being read
‘w’ – Write mode which is used to edit and write new information to the file (any existing
files with the same name will be erased when this mode is activated)
‘a’ – Appending mode, which is used to add new data to the end of the file; that is new
information is automatically amended to the end
‘r+’ – Special read and write mode, which is used to handle both actions when working with
a file.

So, let’s take a look at a quick example.

f=open(“workfile”,”w”)
Print f

This snippet opens the file named “workfile” in writing mode so that we can make changes to
it. Just create the file named “testfile.txt” and leave it blank. If you need to extract a string that
contains all characters in the file, then

file=open(“testfile.text”, “r”)
print file.read()

Using the File Write Method the file write method is that it only requires a single parameter,
which is the string you want to be written. This method is used to add information or content to
an existing file. To start a new line after you write data to the file, you can add an EOL
character. Closing a File when you’re done working, you can use the fh.close() command to
end things.

Conclusion: Hence from above experiment student will understand various file operations like
creation of file, storing data in the files and retrieve data from the files in python.

By Student -______________________________________________________

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 11
Aim: Program to create a package and module for data structures like stack and queues.

Hardware and Software Requirement: P-IV and above, Ram 128 MB, PYTHON IDLE3

Theory:

Stack

It is a sequence of items that are accessible at only one end of the sequence. Think of a stack as
a collection of items that are piled one on top of the other, with access limited to the topmost
item. A stack inserts item on the top of the stack and removes item from the top of the stack. It
has LIFO (last-in / first-out) ordering for the items on the stack. Also, the inbuilt functions in
Python make the code short and simple. To add an item to the top of the list, i.e., to push an
item, we use append() function and to pop out an element we use pop() function. These
functions work quiet efficiently and fast in end operations.

Queue

A queue is a sequential storage structure that permits access only at the two ends of the
sequence. We refer to the ends of the sequence as the front and rear. A queue inserts new
elements at the rear and removes elements from the front of the sequence. You will note that a
queue removes elements in the same order in which they were stored, and hence a queue
provides FIFO (first-in / first-out), or FCFS (first-come / first-served), ordering. Implementing
queue is a bit different. Time plays an important factor here. During the implementation of
stack we used append() and pop() function which was efficient and fast because we inserted
and popped elements from the end of the list, but in queue when insertion and pops are made
from the beginning of the list, it is slow. This occurs due to the properties of list, which is fast
at the end operations but slow at the beginning operations, as all other elements have to be
shifted one by one. So, it’s preferable to use collections.deque over list, which was specially
designed to have fast appends and pops from both the front and back end.

Conclusion: From this experiment we have studied built in functions like pop(), append() used
to perform operations on data structures like stack and queue.

By Student -______________________________________________________

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 12
Aim: Program to create simple socket for basic info exchange between server and client.

Hardware and Software Requirement: P-IV and above, Ram 128 MB, PYTHON IDLE3

Theory:

Sockets are the endpoints of a bidirectional communications channel. Sockets may


communicate within a process, between processes on the same machine, or between processes
on different continents. Sockets may be implemented over a number of different channel types:
Unix domain sockets, TCP, UDP, and so on. The socket library provides specific classes for
handling the common transports as well as a generic interface for handling the rest. One
socket(node) listens on a particular port at an IP, while other socket reaches out to the other to
form a connection. Server forms the listener socket while client reaches out to the server. They
are the real backbones behind web browsing. In simpler terms there is a server and a client.
Socket programming is started by importing the socket library and making a simple socket.

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Here we made a socket instance and passed it two parameters. The first parameter is AF_INET
and the second one is SOCK_STREAM. AF_INET refers to the address family ipv4.

The SOCK_STREAM means connection oriented TCP protocol. Now we can connect to a
server using this socket.
Connecting to a server:

Note that if any error occurs during the creation of a socket then a socket.error is thrown and
we can only connect to a server by knowing its IP.

You can find the ip of the server by using this: $ ping www.google.com

You can also find the ip using python: import socket ip =


socket.gethostbyname('www.google.com') print ip

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Server Socket Methods

Method Description

s.bind() This method binds address (hostname, port


number pair) to socket.

s.listen() This method sets up and start TCP listener.

s.accept() This passively accept TCP client connection,


waiting until connection arrives (blocking).

Client Socket Methods

Method Description

s.recv() This method receives TCP message

s.send() This method transmits TCP message

s.recvfrom() This method receives UDP message

Server :

A server has a bind() method which binds it to a specific ip and port so that it can listen to
incoming requests on that ip and port. A server has a listen() method which puts the server into
listen mode. This allows the server to listen to incoming connections. And last a server has an
accept() and close() method. The accept method initiates a connection with the client and the
close method closes the connection with the client.

Client :

Now we need something with which a server can interact. We could tenet to the server like this
just to know that our server is working. Type these commands in the terminal: # start the server
$ python server.py # keep the above terminal open # now open another terminal and type: $
telnet localhost 12345

Conclusion: From this experiment we studied the client server communication on a network
with the help of socket.

By Student -______________________________________________________

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 13
Aim: A. Write a Perl script to find a factorial of a number using for and until loop if the
number is even number.

B. Demonstrate use of Array

C. Demonstrate use of Hash

Hardware and Software Requirement: P-IV and above, Ram 128 MB, Perl

Theory:

Perl is a general-purpose programming language originally developed for text manipulation


and now used for a wide range of tasks including system administration, web development,
network programming, GUI development, and more.

Perl Installation:

The most up-to-date and current source code, binaries, documentation, news, etc. are available
at the official website of Perl. Perl Official Website − https://www.perl.org/ download only the
binary code applicable for your platform and install Perl. The following are the different ways
to start Perl:

1. Interactive Interpreter You can enter perl and start coding right away in the interactive
interpreter by starting it from the command line.

$perl -e <perl code> # Unix/Linux

or

C:>perl -e <perl code> # Windows/DOS

2. Script from the Command-line A Perl script is a text file, which keeps perl code in it
and it can be executed at the command line by invoking the interpreter on your
application, as in the following –

$perl script.pl # Unix/Linux

or

C:>perl script.pl # Windows/DOS

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
3. Integrated Development Environment

You can run Perl from a graphical user interface (GUI) environment as well. All you
need is a GUI application on your system that supports Perl.

Arrays

An array is a variable that stores an ordered list of scalar values. Array variables are preceded
by an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($)
with the variable name followed by the index of the element in square brackets.

Hashes

A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer
to a single element of a hash, you will use the hash variable name preceded by a "$" sign and
followed by the "key" associated with the value in curly brackets.

Creating Hashes

1. assign a value to a named key on a one-by-one basis

2. use a list, which is converted by taking individual pairs from the list: the first
element of the pair is used as the key, and the second, as the value.

Loop Control Statements


1. for loop: A for loop is a repetition control structure that allows you to efficiently write a
loop that needs to execute a specific number of times.

Syntax: The syntax of a for loop in Perl programming language is –

for ( init; condition; increment )

{ statement(s); }

2. until loop: An until loop statement in Perl programming language repeatedly executes a
target statement as long as a given condition is false.

Syntax: The syntax of an until loop in Perl programming language is –

until(condition)

{ statement(s);}

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Conclusion: From this experiment we have studied creation and insertion of array and hashes
in Perl. We have used the until and for loop structure in perl to find the factorial of a number.

By Student -______________________________________________________

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 14
Aim: Write a Perl script to design a class person and create its objects in Perl

Hardware and Software Requirement: P-IV and above, Ram 128 MB, Perl

Theory: In Perl, a class is corresponds to a Package. To create a class in Perl, we first build a
package. A package is a self-contained unit of user-defined variables and subroutines, which
can be re-used over and over again. They provide a separate namespace within a Perl program
that keeps subroutines and variables from conflicting with those in other packages.

To declare a class named Person in Perl we do:

package Person;

The scope of the package definition extends to the end of the file, or until another package
keyword is encountered.

Creating and Using Objects: To create an instance of a class (an object) we need an object
constructor. This constructor is a method defined within the package. Most programmers
choose to name this object constructor method new, but in Perl one can use any name.

One can use any kind of Perl variable as an object in Perl. Most Perl programmers choose
either references to arrays or hashes.Using a Perl hash reference when creating an object, you
need to supply a constructor. This is a subroutine within a package that returns an object
reference. The object reference is created by blessing a reference to the package's class. Every
method of a class passes first argument as class name.

Conclusion: From this experiment we have studied creation of class and objects in perl.

By Student -______________________________________________________

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 15
Aim: Write a PERL program to demonstrate.

a. File handling (Create, read file).

b. Use of regular expression for text processing in PERL

Hardware and Software Requirement: P-IV and above, Ram 128 MB, Perl

Theory:

Opening a File: To open a file to be read by Perl, you need to use the open function with a
filehandle. The syntax for open is:

open handle, filename;

where handle is the filehandle and filename is the file to be opened, which may include a path.

An example of using an open function is: open (BIGFILE, “file1.dat”);

If you do not specify a directory path, the current directory is assumed. Normally you will
embed an open function inside an if statement to make sure the file was opened properly.
Otherwise, commands later in the program would cause errors. Here’s a typical setup:

if (open (BIGFILE, “datafile.dat”))

{statements to run}

Else

{print “Cannot open the file! \n”; exit 0;}

Closing a File - After you have opened a file and done something with it, you should always
close the file. Closing the file lets the operating system know the file is not in use anymore and
the filehandle is freed.

To close a filehandle, use the close function with the handle name:

open (BIGFILE, “data.txt”);

statements…

close BIGFILE;

Reading a File –

SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
There are a couple of ways to read from an open filehandle. The most common is to use the file
input operator, which is a pair of angle brackets around the filehandle name (just like
<STDIN> to read from the keyboard).

For example:

open (BIGFILE, “data.txt”);


$line=<BIGFILE>;

This will read a line from the file data.txt (referred to by the filehandle and not the name) and
store it in $line.
The line $line=<MFILE>; will read a whole line of input from the MFILE filehandle.
If there is nothing to read, the value “undef” (for undefined) is returned. You can use loops to
read through an entire file.

To test whether the value undef has been detected, use the “defined” keyword:

while(defined($line=<MFILE>))

Regular Expressions –

A regular expression is a string of characters that defines the pattern or patterns you are
viewing. The syntax of regular expressions in Perl is very similar to what you will find within
other regular expression supporting programs, such as sed, grep, and awk.

There are three regular expression operators within Perl.

Match Regular Expression - m//

Substitute Regular Expression - s///

Transliterate Regular Expression - tr///

The match operator, m//, is used to match a string or statement to a regular expression.

Conclusion: From this experiment we have studied create and read operation on file in Perl.
We have used file handle to read data from file and write data to the file. We also studied how
to match regular expressions and substitute regular expressions.

By Student -______________________________________________________

SɅRɅSWɅTI

You might also like