0% found this document useful (0 votes)
3 views57 pages

OSTL Lab Manual

The document contains a series of Python programming experiments aimed at teaching various concepts such as swapping numbers, checking for palindromes, separating even and odd numbers into lists, finding the largest and smallest numbers in a list, merging and sorting lists, comparing string lengths, and identifying unique and common letters in strings. Each experiment includes an aim, theory, source code, output examples, and a conclusion summarizing the learning outcomes. The content is structured as a practical guide for students in a computer engineering course.

Uploaded by

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

OSTL Lab Manual

The document contains a series of Python programming experiments aimed at teaching various concepts such as swapping numbers, checking for palindromes, separating even and odd numbers into lists, finding the largest and smallest numbers in a list, merging and sorting lists, comparing string lengths, and identifying unique and common letters in strings. Each experiment includes an aim, theory, source code, output examples, and a conclusion summarizing the learning outcomes. The content is structured as a practical guide for students in a computer engineering course.

Uploaded by

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

Computer Engineering / SSJCET, Asangaon

EXPERIMENT NO: 1

AIM: Write a python program to swap two numbers and check if the first number
is positive or negative or zero.

THEORY:

Swaping two numbers:

In this example, you will learn to swap two variables without using temporary
variable. In python programming, there is a simple construct to swap variables.
The following code does the same as above but without the use of any temporary
variable.

x,y = y,x

If the variables are both numbers, we can use arithmetic operations to do the same.
It might not look intuitive at the first sight. But if you think about it, its pretty easy
to figure it out.Here are a few example

Addition and Subtraction

x=x+y

y=x-y

x=x-y

Multiplication and Division

x=x*y

y=x/y

x=x/y

Check if the first number is positive or negative or zero:

In this example, you will learn to check whether a number entered by the user is
positive, negative or zero. This problem is solved using if...elif...else and nested
OSTL /CSL 405/ Sem- IV Page 1
Computer Engineering / SSJCET, Asangaon

if...else statement. Here, we have used the if...elif...else statement. We can do the
same thing using nested if statements as follows. A number is positive if it is
greater than zero. We check this in the expression of if. If it is False, the number
will either be zero or negative. This is also tested in subsequent expression.

PROGRAM/SOURCE CODE:

# Python program to swap two variables

# To take input from the user

x = int(input('Enter value of x: '))

y = int(input('Enter value of y: '))

x, y = y, x

print("The value of x after swapping: ",x)

print('The value of y after swapping: ',y)

# To check whethen first number is positive or negative or zero.

if x > 0:

print("x is Positive number")

elif x == 0:

print("x is Zero")

else:

print("x is Negative number")

OUTPUT:

Enter value of x: 75

Enter value of y: 24

The value of x after swapping: 24

OSTL /CSL 405/ Sem- IV Page 2


Computer Engineering / SSJCET, Asangaon

The value of y after swapping: 75

Positive number

CONCLUSION:

Thus we have studied python program to swap two numbers and check if the first
number is positive or negative or zero.

OSTL /CSL 405/ Sem- IV Page 3


Computer Engineering / SSJCET, Asangaon

EXPERIMENT NO: 2

AIM: Write a python program to check whether the given number or string is
palindrome or not.

THEORY:

Check Palindrome in Python

To check whether the given number is a palindrome number or not a palindrome


number in python, you have to ask from user to enter a number to check for
palindrome number as shown in the program given here.

Palindrome number is an integer whose reverse is equal to the number itself, for
example the reverse of 121 is equal to 121 which is the number itself, then it is a
palindrome number, whereas the reverse of 123 is equal to 321 which is not equal
to the number itself, that is 123, therefore it is not a palindrome number.

PROGRAM/SOURCE CODE:

# Program to check if a string

# is palindrome or not

my_str = input("Enter a string: ")

rev_str=''

for i in my_str:

rev_str = i + rev_str

# check if the string is equal to its reverse

if my_str == rev_str:

print("It is palindrome")

else:

print("It is not palindrome")

OSTL /CSL 405/ Sem- IV Page 4


Computer Engineering / SSJCET, Asangaon

OUTPUT:

Enter a string: 12345

It is not palindrome

>>>

Enter a string: 1234321

It is palindrome

>>>

Enter a string: madam

It is palindrome

>>>

Enter a string: happy

It is not palindrome

CONCLUSION:

Thus we have studied a python program to check whether the given number or
string is palindrome or not.

OSTL /CSL 405/ Sem- IV Page 5


Computer Engineering / SSJCET, Asangaon

EXPERIMENT NO: 3

AIM: Write a Python Program to Put Even and Odd elements in a List into Two
Different Lists

THEORY:

Problem Description

The program takes a list and puts the even and odd elements in it into two separate
lists.

Problem Solution

1.Take in the number of elements and store it in a variable.


2. Take in the elements of the list one by one.
3. Use a for loop to traverse through the elements of the list and an if statement to
check if the element is even or odd.
4. If the element is even, append it to a separate list and if it is odd, append it to a
different one.
5. Display the elements in both the lists.
6. Exit.

PROGRAM/SOURCE CODE:

n=int(input("Enter number of elements:"))

a=[]

for i in range(1,n+1):

b=int(input("Enter element:"))

a.append(b)

even=[]

odd=[]

for j in a:

OSTL /CSL 405/ Sem- IV Page 6


Computer Engineering / SSJCET, Asangaon

if(j%2==0):

even.append(j)

else:

odd.append(j)

print("The even list",even)

print("The odd list",odd)

OUTPUT:

Enter number of elements:5

Enter element:3

Enter element:7

Enter element:2

Enter element:10

Enter element:5

The even list [2, 10]

The odd list [3, 7, 5]

CONCLUSION:

Thus we have studied a Python Program to Put Even and Odd elements in a List
into Two Different Lists.

OSTL /CSL 405/ Sem- IV Page 7


Computer Engineering / SSJCET, Asangaon

EXPERIMENT NO: 4

AIM: Write a python program to find largest and smallest number in a list.

THEORY:

A list is a data structure in Python that is a mutable, or changeable, ordered


sequence of elements. Each element or value that is inside of a list is called an
item. Just as strings are defined as characters between quotes, lists are defined by
having values between square brackets [ ].

Lists are great to use when you want to work with many related values. They
enable you to keep data together that belongs together, condense your code, and
perform the same methods and operations on multiple values at once.

Max of list:

Description:The method max returns the elements from the list with maximum
value.

Syntax:Following is the syntax for max() method −

max(list)

Parameters:

list − This is a list from which max valued element to be returned.

Return Value:This method returns the elements from the list with maximum value.

Min of list:

Description:The method min() returns the elements from the list with minimum
value.

Syntax:Following is the syntax for min() method −

min(list)

Parameters:

OSTL /CSL 405/ Sem- IV Page 8


Computer Engineering / SSJCET, Asangaon

list − This is a list from which min valued element to be returned.

Return Value: This method returns the elements from the list with minimum value.

PROGRAM/SOURCE CODE:

lst = []

num = int(input('How many numbers: '))

for n in range(num):

numbers = int(input('Enter number '))

lst.append(numbers)

print("Maximum element in the list is :", max(lst))

print("Minimum element in the list is :", min(lst))

OUTPUT :

How many numbers: 7

Enter number 23

Enter number 12

Enter number 35

Enter number 57

Enter number 35

Enter number 23

Enter number 46

Maximum element in the list is : 57

Minimum element in the list is : 12

OSTL /CSL 405/ Sem- IV Page 9


Computer Engineering / SSJCET, Asangaon

CONCLUSION:

Thus we have studied a python program to find largest and smallest number in a
list.

OSTL /CSL 405/ Sem- IV Page 10


Computer Engineering / SSJCET, Asangaon

EXPERIMENT NO: 5

AIM: Write a menu driven python program to merge and sort two lists.

THEORY:

Problem Description:

The program takes two lists, merges them and sorts the merged list.

Problem Solution:

1. Take in the number of elements for the first list and store it in a variable.
2. Take in the elements of the list one by one.
3. Similarly, take in the elements for the second list also.
4. Merge both the lists using the ‘+’ operator and then sort the list.
5. Display the elements in the sorted list.
6. Exit.

Program Explanation:

1. User must enter the number of elements for the first list and store it in a variable.
2. User must then enter the elements of the list one by one using a for loop and
store it in a list.
3. User must similarly enter the elements of the second list one by one.
4. The ‘+’ operator is then used to merge both the lists.
5. The sort function then sorts the list in ascending order.
6. The sorted list is then printed.

PROGRAM/SOURCE CODE:

a=[]

c=[]

def mergelist():

n1=int(input("Enter number of elements:"))

for i in range(1,n1+1):

OSTL /CSL 405/ Sem- IV Page 11


Computer Engineering / SSJCET, Asangaon

b=int(input("Enter element:"))

a.append(b)

n2=int(input("Enter number of elements:"))

for i in range(1,n2+1):

d=int(input("Enter element:"))

c.append(d)

new=a+c

print("Merged list is:",new)

def sorting():

n1=int(input("Enter number of elements:"))

for i in range(1,n1+1):

b=int(input("Enter element:"))

a.append(b)

n2=int(input("Enter number of elements:"))

for i in range(1,n2+1):

d=int(input("Enter element:"))

c.append(d)

new=a+c

new.sort()

print("Sorted list is:",new)

while True:

OSTL /CSL 405/ Sem- IV Page 12


Computer Engineering / SSJCET, Asangaon

print("\nMenu\n(M)erging List\n(S)Sorting List\n(Q)uit")

choice = input(">>> ").lower().rstrip()

if choice=="q":

break

elif choice=="m":

mergelist()

elif choice=="s":

sorting()

else:

print("Invalid choice, please choose again\n")

print("Thank you for playing.")

OUTPUT:

Menu

(M)erging List

(S)Sorting List

(Q)uit

>>> m

Enter number of elements:3

Enter element:12

Enter element:23

Enter element:34

OSTL /CSL 405/ Sem- IV Page 13


Computer Engineering / SSJCET, Asangaon

Enter number of elements:4

Enter element:23

Enter element:14

Enter element:245

Enter element:45

Merged list is: [12, 23, 34, 23, 14, 245, 45]

Menu

(M)erging List

(S)Sorting List

(Q)uit

>>> s

Enter number of elements:3

Enter element:23

Enter element:324

Enter element:21

Enter number of elements:6

Enter element:4

Enter element:23

Enter element:6

Enter element:3

Enter element:78

Enter element:34

OSTL /CSL 405/ Sem- IV Page 14


Computer Engineering / SSJCET, Asangaon

Sorted list is: [3, 4, 6, 21, 23, 23, 34, 78, 324]

Menu

(M)erging List

(S)Sorting List

(Q)uit

>>> q

Thank you for playing.

CONCLUSION:

Thus we have studied menu driven python program to merge and sort two lists.

OSTL /CSL 405/ Sem- IV Page 15


Computer Engineering / SSJCET, Asangaon

EXPERIMENT NO: 6

AIM: Write a Python Program to Take in Two Strings and Display the Larger
String without Using Built-in Functions

THEORY:

Problem Description

The program takes in two strings and display the larger string without using built-
in function.

Problem Solution

1. Take in two strings from the user and store it in separate variables.
2. Initialize the two count variables to zero.
3. Use a for loop to traverse through the characters in the string and increment the
count variables each time a character is encountered.
4. Compare the count variables of both the strings.
5. Print the larger string.
6. Exit.

PROGRAM/SOURCE CODE:

string1=input("Enter first string: ")

string2=input("Enter second string: ")

count1=0

count2=0

for i in string1:

count1=count1+1

for j in string2:

count2=count2+1

if(count1<count2):

OSTL /CSL 405/ Sem- IV Page 16


Computer Engineering / SSJCET, Asangaon

print("Larger string is: ", string2)

elif(count1==count2):

print("Both strings are equal.")

else:

print("Larger string is: ", string1)

OUTPUT:

Enter first string: Bangalore

Enter second string: Mumbai

Larger string is: Bangalore

>>>

Enter first string: Nashik

Enter second string: Jaipur

Both strings are equal.

CONCLUSION:

Thus we have studied a Python Program to Take in Two Strings and Display the
Larger String without Using Built-in Functions.

OSTL /CSL 405/ Sem- IV Page 17


Computer Engineering / SSJCET, Asangaon

EXPERIMENT NO: 7(A)

AIM: Write a Python Program that Displays which Letters are in the First String
but not in the Second

THEORY:

Problem Description

The program takes two strings and displays which letters are in the first string but
not in the second string.

Problem Solution

1. Enter two input strings and store it in separate variables.


2. Convert both of the strings into sets and find which letters are present in the first
string but not in the second string.
3. Store the letters in a list.
4. Use a for loop to print the letters of the list.
5. Exit.

Program Explanation

1. User must enter two input strings and store it in separate variables.
2. Both of the strings are converted into sets and the letters which are in the first
string but not in the second string are found using the ‘-‘ operator.
3. These letters are stored in a list.
4. A for loop is used to print the letters of the list.

PROGRAM/SOURCE CODE:

s1=input("Enter first string: ")

s2=input("Enter second string: ")

a=list(set(s1)-set(s2))

print("The letters are:")

for i in a:

OSTL /CSL 405/ Sem- IV Page 18


Computer Engineering / SSJCET, Asangaon

print(i)

OUTPUT:

Case 1:

Enter first string: Computer

Enter second string: Monitor

The letters are:

Case 2:

Enter first string: Python

Enter second string: Programming language

The letters are:

CONCLUSION:

Thus we have studied a Python Program that Displays which Letters are in the
First String but not in the Second.

OSTL /CSL 405/ Sem- IV Page 19


Computer Engineering / SSJCET, Asangaon

EXPERIMENT NO: 7(B)

AIM: Write a Python Program that Displays which Letters are Present in Both the
Strings

THEORY:

Problem Description

The program takes two strings and displays which letters are present in both the
strings.

Problem Solution

1. Enter two input strings and store it in separate variables.


2. Convert both of the strings into sets and find the union between both the sets.
3. Store the letters in a list.
4. Use a for loop to print the letters of the list.
5. Exit.

Program Explanation

1. User must enter two input strings and store it in separate variables.
2. Both of the strings are converted into sets and the union of both the sets are
found using the ‘|’ operator.
3. These letters are stored in a list.
4. A for loop is used to print the letters of the list.

PROGRAM/SOURCE CODE:

s1=input("Enter first string: ")

s2=input("Enter second string: ")

a=list(set(s1)|set(s2))

print("The letters are:")

OSTL /CSL 405/ Sem- IV Page 20


Computer Engineering / SSJCET, Asangaon

for i in a:

print(i)

Output:

Case 1:

Enter first string: hello

Enter second string: world

The letters are:

Case 2:

Enter first string: test

Enter second string: string

The letters are:

OSTL /CSL 405/ Sem- IV Page 21


Computer Engineering / SSJCET, Asangaon

CONCLUSION:

Thus we have studied a Python Program that Displays which Letters are Present in
Both the Strings

OSTL /CSL 405/ Sem- IV Page 22


Computer Engineering / SSJCET, Asangaon

EXPERIMENT NO: 8

AIM: Write a menu driven program to demonstrate use of Dictionary in Python.

THEORY:

Create a new dictionary

# In order to construct a dictionary you can start with an empty one. >>>mydict={}
# This will create a dictionary, which has an initially six key-value pairs, where
iphone* is the key and years the values

Add a value to the dictionary

You can assign to an individual dictionary entry to add it or modify it

#the syntax is: mydict[key] = "value"

Remove a key and it's value

You can remove key-value pairs with the del operator

#the syntax is: del mydict[key]

Check the length

The len() function gives the number of pairs in the dictionary.

#the syntax is: len(mydict)

Test the dictionary

Check if a key exists in a given dictionary by using the in operator like this:

#the syntax is: mydict = {'a' : 'one', 'b' : 'two'}

Get a value of a specified key

#the syntax is: mydict.get(key, "none")

Print all keys with a for loop

For k in mydict:
OSTL /CSL 405/ Sem- IV Page 23
Computer Engineering / SSJCET, Asangaon

print k

Print all key and values

forkey,val in mydict.items():

print key, "=>", val

Get only the keys from the dictionary

phones = mydict.keys()

print phones

Printing with pprint

pprint.pprint(released)

Sorting the dictionary

for key, value in sorted(mydict.items()):

print key, value

Counting

count = {}

for element in mydict:

count[element] = count.get(element, 0) + 1

print count

PROGRAM/SOURCE CODE:

choice="null"

while choice!="q":

print("\nMenu")

print("(C)reate a iphone Dictionary")

OSTL /CSL 405/ Sem- IV Page 24


Computer Engineering / SSJCET, Asangaon

print("(A)dd new version of iphone")

print("(D)elete oldest version of iphone")

print("(L)ength of dictionary")

print("(F)ind 'iphone 5' in the dictionary")

print("(G)et released year of 'iphone 3G'")

print("(R)eleased versions of iphone")

print("(S)orted versions of iphone")

print("(Q)uit")

choice = input(">>> ").lower().rstrip()

if choice=="q":

break

elif choice=="c":

released = {

"iphone" : 2007,

"iphone 3G" : 2008,

"iphone 3GS" : 2009,

"iphone 4" : 2010,

"iphone 4S" : 2011,

"iphone 5" : 2012

print ("Iphone Dictionary created:")

print (released)

elif choice=="a":

OSTL /CSL 405/ Sem- IV Page 25


Computer Engineering / SSJCET, Asangaon

released["iphone 5S"] = 2013

print ("Modified dictionary")

print (released)

elif choice=="d":

del released["iphone"]

print ("Modified dictionary")

print (released)

elif choice=="l":

print ("Length of dictionary")

print (len(released))

elif choice=="f":

for item in released:

if "iphone 5" in released:

print ("Key found")

break

else:

print ("No keys found")

elif choice=="g":

print ("Released year of iphone 3G")

print (released.get("iphone 3G", "none"))

elif choice=="r":

print ("All iphone releases so far: ")

print ("-" * 20)

OSTL /CSL 405/ Sem- IV Page 26


Computer Engineering / SSJCET, Asangaon

for key,val in released.items():

print (key, "=>", val)

elif choice=="s":

print ("All iphone releases so far in sorted order of version: ")

for phones in sorted(released, key=len):

print (phones, released[phones])

else:

print("Invalid choice, please choose again\n")

print("Thank you for playing.")

OUTPUT:

Menu

(C)reate a iphone Dictionary

(A)dd new version of iphone

(D)elete oldest version of iphone

(L)ength of dictionary

(F)ind 'iphone 5' in the dictionary

(G)et released year of 'iphone 3G'

(R)eleased versions of iphone

(S)orted versions of iphone

(Q)uit

>>> c

OSTL /CSL 405/ Sem- IV Page 27


Computer Engineering / SSJCET, Asangaon

Iphone Dictionary created:

{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone
4S': 2011, 'iphone 5': 2012}

Menu

(C)reate a iphone Dictionary

(A)dd new version of iphone

(D)elete oldest version of iphone

(L)ength of dictionary

(F)ind 'iphone 5' in the dictionary

(G)et released year of 'iphone 3G'

(R)eleased versions of iphone

(S)orted versions of iphone

(Q)uit

>>> a

Modified dictionary

{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone
4S': 2011, 'iphone 5': 2012, 'iphone 5S': 2013}

Menu

(C)reate a iphone Dictionary

(A)dd new version of iphone

(D)elete oldest version of iphone

(L)ength of dictionary
OSTL /CSL 405/ Sem- IV Page 28
Computer Engineering / SSJCET, Asangaon

(F)ind 'iphone 5' in the dictionary

(G)et released year of 'iphone 3G'

(R)eleased versions of iphone

(S)orted versions of iphone

(Q)uit

>>> d

Modified dictionary

{'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone
5': 2012, 'iphone 5S': 2013}

Menu

(C)reate a iphone Dictionary

(A)dd new version of iphone

(D)elete oldest version of iphone

(L)ength of dictionary

(F)ind 'iphone 5' in the dictionary

(G)et released year of 'iphone 3G'

(R)eleased versions of iphone

(S)orted versions of iphone

(Q)uit

>>> l

Length of dictionary

OSTL /CSL 405/ Sem- IV Page 29


Computer Engineering / SSJCET, Asangaon

Menu

(C)reate a iphone Dictionary

(A)dd new version of iphone

(D)elete oldest version of iphone

(L)ength of dictionary

(F)ind 'iphone 5' in the dictionary

(G)et released year of 'iphone 3G'

(R)eleased versions of iphone

(S)orted versions of iphone

(Q)uit

>>> f

Key found

Menu

(C)reate a iphone Dictionary

(A)dd new version of iphone

(D)elete oldest version of iphone

(L)ength of dictionary

(F)ind 'iphone 5' in the dictionary

(G)et released year of 'iphone 3G'

(R)eleased versions of iphone

(S)orted versions of iphone

OSTL /CSL 405/ Sem- IV Page 30


Computer Engineering / SSJCET, Asangaon

(Q)uit

>>> g

Released year of iphone 3G

2008

Menu

(C)reate a iphone Dictionary

(A)dd new version of iphone

(D)elete oldest version of iphone

(L)ength of dictionary

(F)ind 'iphone 5' in the dictionary

(G)et released year of 'iphone 3G'

(R)eleased versions of iphone

(S)orted versions of iphone

(Q)uit

>>> r

All iphone releases so far:

--------------------

iphone 3G => 2008

iphone 3GS => 2009

iphone 4 => 2010

iphone 4S => 2011

iphone 5 => 2012

OSTL /CSL 405/ Sem- IV Page 31


Computer Engineering / SSJCET, Asangaon

iphone 5S => 2013

Menu

(C)reate a iphone Dictionary

(A)dd new version of iphone

(D)elete oldest version of iphone

(L)ength of dictionary

(F)ind 'iphone 5' in the dictionary

(G)et released year of 'iphone 3G'

(R)eleased versions of iphone

(S)orted versions of iphone

(Q)uit

>>> s

All iphone releases so far in sorted order of version:

iphone 4 2010

iphone 5 2012

iphone 3G 2008

iphone 4S 2011

iphone 5S 2013

iphone 3GS 2009

Menu

(C)reate a iphone Dictionary

OSTL /CSL 405/ Sem- IV Page 32


Computer Engineering / SSJCET, Asangaon

(A)dd new version of iphone

(D)elete oldest version of iphone

(L)ength of dictionary

(F)ind 'iphone 5' in the dictionary

(G)et released year of 'iphone 3G'

(R)eleased versions of iphone

(S)orted versions of iphone

(Q)uit

>>> q

Thank you for playing.

CONCLUSION:

Thus we have studied a menu driven program to demonstrate use of Dictionary in


Python.

OSTL /CSL 405/ Sem- IV Page 33


Computer Engineering / SSJCET, Asangaon

EXPERIMENT NO: 9

AIM: Write a python program to demonstrate multiple inheritance.

THEORY:

Python Multilevel Inheritance Example

The classes Person and Student are superclass here and Resident is the subclass.
The class Resident extends both Person and Student to inherit the properties of
both classes. The example is easily understandable if you have the slightest
knowledge of python class and python inheritance. This code yields the following
output.

PROGRAM/SOURCE CODE:

#definition of the class starts here

class Person:

#defining constructor

def __init__(self, personName, personAge):

self.name = personName

self.age = personAge

#defining class methods

def showName(self):

print(self.name)

def showAge(self):

print(self.age)

#end of class definition

# defining another class

OSTL /CSL 405/ Sem- IV Page 34


Computer Engineering / SSJCET, Asangaon

class Student: # Person is the

def __init__(self, studentId):

self.studentId = studentId

def getId(self):

return self.studentId

class Resident(Person, Student): # extends both Person and Student class

def __init__(self, name, age, id):

Person.__init__(self, name, age)

Student.__init__(self, id)

# Create an object of the subclass

resident1 = Resident('John', 30, '102')

resident1.showName()

print(resident1.getId())

Output:

John

102

CONCLUSION:

Thus we have studied a python program to demonstrate multiple inheritance.

OSTL /CSL 405/ Sem- IV Page 35


Computer Engineering / SSJCET, Asangaon

EXPERIMENT NO: 10

AIM: Write a python program to demonstrate exception handling using try with
except and finally.

THEORY:

Exception Handling in Python

Overview

In this post we will cover how Python handles errors with exceptions.

What is an Exception?

An exception is an error that happens during execution of a program. When


thaterror occurs, Python generate an exception that can be handled, which avoids
yourprogram to crash.

Exception Errors

Below is some common exceptions errors in Python:

IOError

If the file cannot be opened.

ImportError

If python cannot find the module

ValueError

Raised when a built-in operation or function receives an argument that has the

right type but an inappropriate value

OSTL /CSL 405/ Sem- IV Page 36


Computer Engineering / SSJCET, Asangaon

KeyboardInterrupt

Raised when the user hits the interrupt key (normally Control-C or Delete)

EOFError

Raised when one of the built-in functions (input() or raw_input()) hits an

end-of-file condition (EOF) without reading any data

How does it work?

The error handling is done through the use of exceptions that are caught in try

blocks and handled in except blocks. If an error is encountered, a try block

code execution is stopped and transferred down to the except block.

In addition to using an except block after the try block, you can also use the

finally block.

The code in the finally block will be executed regardless of whether an exception

occurs.

doing_different_exception_handling

Exceptions in the else clause are not handled by the preceding except clauses.

Make sure that the else clause is run before the finally block.

PROGRAM/SOURCE CODE:

try:

fob = open('test', 'r')

try:

OSTL /CSL 405/ Sem- IV Page 37


Computer Engineering / SSJCET, Asangaon

fob.write("It's my test file to verify try-finally in exception handling!!")

print ('try block executed')

finally:

fob.close()

print ('finally block executed to close the file')

except IOError:

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

try:

a = int(input("Enter a positive integer value: "))

if a <= 0:

raise ValueError("This is not a positive number!!")

except ValueError as ve:

print(ve)

OUTPUT:

Error: can't find file or read data

Enter a positive integer value: -5

This is not a positive number!!

CONCLUSION:

Thus we have studied a python program to demonstrate exception handling using


try with except and finally.

OSTL /CSL 405/ Sem- IV Page 38


Computer Engineering / SSJCET, Asangaon

EXPERIMENT NO: 11

AIM: Create a package and module for data structure: Queue and Stack.

THEORY:

Stack and Queue in Python using queue Module

A simple python List can act as queue and stack as well. Queue mechanism is used
widely and for many purposes in daily life. A queue follows FIFO rule(First In
First Out) and is used in programming for sorting and for many more things.
Python provides Class queue as a module which has to be generally created in
languages such as C/C++ and Java.

A stack is a data structure with two main operations: push and pop.

Push: append an element on top of the stack

Pop: remove an element from the top of the stack

Think of a tray holder in a dining hall as a real world example of what a stack is.
You can take out one tray from the top of the holder, and you can put a different
one on top of the holder. The interesting fact with a stack is that you can only
operate on the data on top of it.

For this reason, stacks are referred to as a LIFO or a FILO data structure.

LIFO = Last in First out

FILO = First in Last out

The two terms points to the same characteristic of the stack: if you push an element
to the stack, you can remove it only if you remove the other elements that are
added to the stack after itself (think about removing the element 1 from the stack).

When are stacks useful?

Stacks are useful in two ways:

Tracing back to access previous elements/operations

OSTL /CSL 405/ Sem- IV Page 39


Computer Engineering / SSJCET, Asangaon

For example, undo operations in editors are like popping a code change that was
just pushed in the stack of edit history. Similarly, back operations in browsers are
like popping a site visit that was just pushed in the stack of browser history.

2. Matching recursive elements/operations

For example, a stack comes in handy when checking if an operation “(5 + 6) + ((7
* 9) + 9) + 10)” is a valid syntax (see sample problem 3 for details). Another use
case is to keep track of recursions in a code. Each call to the recursive function is
pushed onto the stack so that it can be executed once lower recursions are done
with their execution.

A queue is a data structure with two main operations: enqueue and dequeue.

enqueue: append an element to the tail of the queue

dequeue: remove an element from the head of the queue

Queues should be easier to understand, since queues in computer science are just
like queues in real life. Think of a long line in front of a busy restaurant. Each
person will be “enqueued” to the line and once they reach the head of the line, they
are “dequeued” and enters the restaurant.

Whereas stacks are to as LIFO or FILO, queues are referred to as a FIFO or LILO
data structure.

FIFO = First in First out

LILO = Last in Last out

The two terms points to the same characteristic of the queue: the first person to join
the queue is the first person to get out of the queue to enter the restaurant. The last
person to join the queue is the last person to enter the restaurant.

When are queues useful?

Queues are used whenever you want to process things one at a time as they come
in.

Some examples are, uploading bunch of images, printing multiple documents, and
processing thousands of requests to a web server.

OSTL /CSL 405/ Sem- IV Page 40


Computer Engineering / SSJCET, Asangaon

PROGRAM/SOURCE CODE:

import queue

#..................................................

#Queue program

#..................................................

print ("_________________________________________")

print ("Implementing Queue")

print ("_________________________________________")

L = queue.Queue(maxsize=6)

# qsize() give the maxsize

# of the Queue

print(L.qsize())

L.put(5)

L.put(9)

L.put(1)

L.put(7)

# Return Boolean for Full

# Queue

print("Full: ", L.full())

OSTL /CSL 405/ Sem- IV Page 41


Computer Engineering / SSJCET, Asangaon

L.put(9)

L.put(10)

print("Full: ", L.full())

print(L.get())

print(L.get())

print(L.get())

# Return Boolean for Empty

# Queue

print("Empty: ", L.empty())

print(L.get())

print(L.get())

print(L.get())

print("Empty: ", L.empty())

print("Full: ", L.full())

# This would result into Infinite

# Loop as the Queue is empty.

# print(L.get())

#..................................................
OSTL /CSL 405/ Sem- IV Page 42
Computer Engineering / SSJCET, Asangaon

#Stack program

#..................................................

print ("_________________________________________")

print ("Implementing Stack")

print ("_________________________________________")

S = queue.LifoQueue(maxsize=6)

# qsize() give the maxsize of

# the Queue

print(S.qsize())

# Data Inserted as 5->9->1->7,

# same as Queue

S.put(5)

S.put(9)

S.put(1)

S.put(7)

S.put(9)

S.put(10)

print("Full: ", S.full())

print("Size: ", S.qsize())

# Data will be accessed in the

OSTL /CSL 405/ Sem- IV Page 43


Computer Engineering / SSJCET, Asangaon

# reverse order Reverse of that

# of Queue

print(S.get())

print(S.get())

print(S.get())

print(S.get())

print(S.get())

print(S.get())

print("Empty: ", S.empty())

OUTPUT:

_________________________________________

Implementing Queue

_________________________________________

Full: False

Full: True

Empty: False

OSTL /CSL 405/ Sem- IV Page 44


Computer Engineering / SSJCET, Asangaon

10

Empty: True

Full: False

_________________________________________

Implementing Stack

_________________________________________

Full: True

Size: 6

10

Empty: True

CONCLUSION:

Thus we have studied a package and module for data structure: Queue and Stack.

OSTL /CSL 405/ Sem- IV Page 45


Computer Engineering / SSJCET, Asangaon

EXPERIMENT NO: 12

AIM: Creation of simple socket for basic information exchange between server &
client

THEORY:

A simple server-client program :

To understand python socket programming, we need to know about three


interesting topics – Socket Server, Socket Client and Socket.

So, what is a server? Well, a server is a software that waits for client requests and
serves or processes them accordingly.

On the other hand, a client is requester of this service. A client program request for
some resources to the server and server responds to that request.

Socket is the endpoint of a bidirectional communications channel between server


and client. Sockets may communicate within a process, between processes on the
same machine, or between processes on different machines. For any
communication with a remote program, we have to connect through a socket port.

The main objective of this socket programming tutorial is to get introduce you how
socket server and client communicate with each other. You will also learn how to
write python socket server program.

Python Socket Example

We have said earlier that a socket client requests for some resources to the socket
server and the server responds to that request.

So we will design both server and client model so that each can communicate with
them. The steps can be considered like this.

Python socket server program executes at first and wait for any request

Python socket client program will initiate the conversation at first.

Then server program will response accordingly to client requests.

OSTL /CSL 405/ Sem- IV Page 46


Computer Engineering / SSJCET, Asangaon

Client program will terminate if user enters “bye” message. Server program will
also terminate when client program terminates, this is optional and we can keep
server program running indefinitely or terminate with some specific command in
client request.

Python Socket Server

We will save python socket server program as socket_server.py. To use python


socket connection, we need to import socket module.

Then, sequentially we need to perform some task to establish connection between


server and client.

We can obtain host address by using socket.gethostname() function. It is


recommended to user port address above 1024 because port number lesser than
1024 are reserved for standard internet protocol.

See the below python socket server example code, the comments will help you to
understand the code.

So our python socket server is running on port 5000 and it will wait for client
request. If you want server to not quit when client connection is closed, just
remove the if condition and break statement. Python while loop is used to run the
server program indefinitely and keep waiting for client request.

Python Socket Client

We will save python socket client program as socket_client.py. This program is


similar to the server program, except binding.

The main difference between server and client program is, in server program, it
needs to bind host address and port address together.

See the below python socket client example code, the comment will help you to
understand the code.

Python Socket Programming Output

To see the output, first run the socket server program. Then run the socket client
program. After that, write something from client program. Then again write reply

OSTL /CSL 405/ Sem- IV Page 47


Computer Engineering / SSJCET, Asangaon

from server program. At last, write bye from client program to terminate both
program.

PROGRAM/SOURCE CODE:

socket_server.py

import socket

def server_program():

# get the hostname

host = socket.gethostname()

port = 5000 # initiate port no above 1024

server_socket = socket.socket() # get instance

# look closely. The bind() function takes tuple as argument

server_socket.bind((host, port)) # bind host address and port together

# configure how many client the server can listen simultaneously

server_socket.listen(2)

conn, address = server_socket.accept() # accept new connection

print("Connection from: " + str(address))

while True:

# receive data stream. it won't accept data packet greater than 1024 bytes

data = conn.recv(1024).decode()

if not data:

# if data is not received break

OSTL /CSL 405/ Sem- IV Page 48


Computer Engineering / SSJCET, Asangaon

break

print("from connected user: " + str(data))

data = input(' -> ')

conn.send(data.encode()) # send data to the client

conn.close() # close the connection

if __name__ == '__main__':

server_program()

socket_client.py

import socket

def client_program():

host = socket.gethostname() # as both code is running on same pc

port = 5000 # socket server port number

client_socket = socket.socket() # instantiate

client_socket.connect((host, port)) # connect to the server

message = input(" -> ") # take input

while message.lower().strip() != 'bye':

client_socket.send(message.encode()) # send message

data = client_socket.recv(1024).decode() # receive response

print('Received from server: ' + data) # show in terminal

message = input(" -> ") # again take input

OSTL /CSL 405/ Sem- IV Page 49


Computer Engineering / SSJCET, Asangaon

client_socket.close() # close the connection

if __name__ == '__main__':

client_program()

OUTPUT:

$ python3.6 socket_server.py

Connection from: ('127.0.0.1', 57822)

from connected user: Hi

-> Hello

from connected user: How are you?

-> Good

from connected user: Awesome!

-> Ok then, bye!

………………………………………………………………………………………

$ python3.6 socket_client.py

-> Hi

Received from server: Hello

-> How are you?

Received from server: Good

-> Awesome!

Received from server: Ok then, bye!

-> Bye

OSTL /CSL 405/ Sem- IV Page 50


Computer Engineering / SSJCET, Asangaon

CONCLUSION:

Thus we have studied a Creation of simple socket for basic information exchange
between server & client

OSTL /CSL 405/ Sem- IV Page 51


Computer Engineering / SSJCET, Asangaon

EXPERIMENT NO: 13

AIM: Write a perl script to demonstrate use of Array.

THEORY:

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.

Array variables are prefixed with the @ sign and are populated using either
parentheses or the qw operator. For example −

@array = (1, 2, 'Hello');

@array = qw/This is an array/;

The second line uses the qw// operator, which returns a list of strings, separating
the delimited string by white space. In this example, this leads to a four-element
array; the first element is 'this' and last (fourth) is 'array'. This means that you can
use different lines as follows −

@days = qw/Monday

Tuesday

...

Sunday/;

You can also populate an array by assigning each value individually as follows −

$array[0] = 'Monday';

...

$array[6] = 'Sunday';

Perl provides a number of useful functions to add and remove elements in an array.
You may have a question what is a function? So far you have used print function to

OSTL /CSL 405/ Sem- IV Page 52


Computer Engineering / SSJCET, Asangaon

print various values. Similarly there are various other functions or sometime called
sub-routines, which can be used for various other functionalities.

Sr.No. Types & Description

push @ARRAY, LIST


1
Pushes the values of the list onto the end of the array.

pop @ARRAY
2
Pops off and returns the last value of the array.

shift @ARRAY
3 Shifts the first value of the array off and returns it, shortening the array by 1
and moving everything down.

unshift @ARRAY, LIST


4 Prepends list to the front of the array, and returns the number of elements in
the new array.

PROGRAM/SOURCE CODE:
#!/usr/bin/perl
# create a simple array
@coins = ("Quarter","Dime","Nickel");
print "1. \@coins = @coins\n";

# add one element at the end of the array


push(@coins, "Penny");
print "2. \@coins = @coins\n";

# add one element at the beginning of the array


unshift(@coins, "Dollar");
print "3. \@coins = @coins\n";

# remove one element from the last of the array.


pop(@coins);

OSTL /CSL 405/ Sem- IV Page 53


Computer Engineering / SSJCET, Asangaon

print "4. \@coins = @coins\n";

# remove one element from the beginning of the array.


shift(@coins);
print "5. \@coins = @coins\n";

OUTPUT:

1. @coins = Quarter Dime Nickel


2. @coins = Quarter Dime Nickel Penny
3. @coins = Dollar Quarter Dime Nickel Penny
4. @coins = Dollar Quarter Dime Nickel
5. @coins = Quarter Dime Nickel

CONCLUSION:

Thus we have studied a perl script to demonstrate use of Array.

OSTL /CSL 405/ Sem- IV Page 54


Computer Engineering / SSJCET, Asangaon

EXPERIMENT NO: 14

AIM: Write a perl script to send email.

THEORY:

Sending a Plain Message

If you are working on Linux/Unix machine then you can simply use sendmail
utility inside your Perl program to send email. Here is a sample script that can send
an email to a given email ID. Just make sure the given path for sendmail utility is
correct. This may be different for your Linux/Unix machine.

Actually, this script is a client email script, which will draft email and submit to the
server running locally on your Linux/Unix machine. This script will not be
responsible for sending email to actual destination. So you have to make sure email
server is properly configured and running on your machine to send email to the
given email ID.

Sending an HTML Message

If you want to send HTML formatted email using sendmail, then you simply need
to add Content-type: text/html\n in the header part of the email.

PROGRAM/SOURCE CODE:

Simple plain message

#!/usr/bin/perl

$to = '[email protected]';

$from = '[email protected]';

$subject = 'Test Email';

$message = 'This is test email sent by Perl Script';

OSTL /CSL 405/ Sem- IV Page 55


Computer Engineering / SSJCET, Asangaon

open MAIL, "|/usr/sbin/sendmail -t");

# Email Header

print MAIL "To: $to\n";

print MAIL "From: $from\n";

print MAIL "Subject: $subject\n\n";

# Email Body

print MAIL $message;

close(MAIL);

print "Email Sent Successfully\n";

Sending a HTML Message:

#!/usr/bin/perl

$to = '[email protected]';

$from = '[email protected]';

$subject = 'Test Email';

$message = '<h1>This is test email sent by Perl Script</h1>';

open(MAIL, "|/usr/sbin/sendmail -t");

# Email Header

print MAIL "To: $to\n";

print MAIL "From: $from\n";

print MAIL "Subject: $subject\n\n";

print MAIL "Content-type: text/html\n";

# Email Body

OSTL /CSL 405/ Sem- IV Page 56


Computer Engineering / SSJCET, Asangaon

print MAIL $message;

close(MAIL);

print "Email Sent Successfully\n";

CONCLUSION:

Thus we have studied a perl script to send email.

OSTL /CSL 405/ Sem- IV Page 57

You might also like