OSTL Lab Manual
OSTL Lab Manual
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:
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
x=x+y
y=x-y
x=x-y
x=x*y
y=x/y
x=x/y
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:
x, y = y, x
if x > 0:
elif x == 0:
print("x is Zero")
else:
OUTPUT:
Enter value of x: 75
Enter value of y: 24
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.
EXPERIMENT NO: 2
AIM: Write a python program to check whether the given number or string is
palindrome or not.
THEORY:
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:
# is palindrome or not
rev_str=''
for i in my_str:
rev_str = i + rev_str
if my_str == rev_str:
print("It is palindrome")
else:
OUTPUT:
It is not palindrome
>>>
It is palindrome
>>>
It is palindrome
>>>
It is not palindrome
CONCLUSION:
Thus we have studied a python program to check whether the given number or
string is palindrome or not.
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
PROGRAM/SOURCE CODE:
a=[]
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
even=[]
odd=[]
for j in a:
if(j%2==0):
even.append(j)
else:
odd.append(j)
OUTPUT:
Enter element:3
Enter element:7
Enter element:2
Enter element:10
Enter element:5
CONCLUSION:
Thus we have studied a Python Program to Put Even and Odd elements in a List
into Two Different Lists.
EXPERIMENT NO: 4
AIM: Write a python program to find largest and smallest number in a list.
THEORY:
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.
max(list)
Parameters:
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.
min(list)
Parameters:
Return Value: This method returns the elements from the list with minimum value.
PROGRAM/SOURCE CODE:
lst = []
for n in range(num):
lst.append(numbers)
OUTPUT :
Enter number 23
Enter number 12
Enter number 35
Enter number 57
Enter number 35
Enter number 23
Enter number 46
CONCLUSION:
Thus we have studied a python program to find largest and smallest number in a
list.
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():
for i in range(1,n1+1):
b=int(input("Enter element:"))
a.append(b)
for i in range(1,n2+1):
d=int(input("Enter element:"))
c.append(d)
new=a+c
def sorting():
for i in range(1,n1+1):
b=int(input("Enter element:"))
a.append(b)
for i in range(1,n2+1):
d=int(input("Enter element:"))
c.append(d)
new=a+c
new.sort()
while True:
if choice=="q":
break
elif choice=="m":
mergelist()
elif choice=="s":
sorting()
else:
OUTPUT:
Menu
(M)erging List
(S)Sorting List
(Q)uit
>>> m
Enter element:12
Enter element:23
Enter element:34
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 element:23
Enter element:324
Enter element:21
Enter element:4
Enter element:23
Enter element:6
Enter element:3
Enter element:78
Enter element:34
Sorted list is: [3, 4, 6, 21, 23, 23, 34, 78, 324]
Menu
(M)erging List
(S)Sorting List
(Q)uit
>>> q
CONCLUSION:
Thus we have studied menu driven python program to merge and sort two lists.
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:
count1=0
count2=0
for i in string1:
count1=count1+1
for j in string2:
count2=count2+1
if(count1<count2):
elif(count1==count2):
else:
OUTPUT:
>>>
CONCLUSION:
Thus we have studied a Python Program to Take in Two Strings and Display the
Larger String without Using Built-in Functions.
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
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:
a=list(set(s1)-set(s2))
for i in a:
print(i)
OUTPUT:
Case 1:
Case 2:
CONCLUSION:
Thus we have studied a Python Program that Displays which Letters are in the
First String but not in the Second.
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
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:
a=list(set(s1)|set(s2))
for i in a:
print(i)
Output:
Case 1:
Case 2:
CONCLUSION:
Thus we have studied a Python Program that Displays which Letters are Present in
Both the Strings
EXPERIMENT NO: 8
THEORY:
# 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
Check if a key exists in a given dictionary by using the in operator like this:
For k in mydict:
OSTL /CSL 405/ Sem- IV Page 23
Computer Engineering / SSJCET, Asangaon
print k
forkey,val in mydict.items():
phones = mydict.keys()
print phones
pprint.pprint(released)
Counting
count = {}
count[element] = count.get(element, 0) + 1
print count
PROGRAM/SOURCE CODE:
choice="null"
while choice!="q":
print("\nMenu")
print("(L)ength of dictionary")
print("(Q)uit")
if choice=="q":
break
elif choice=="c":
released = {
"iphone" : 2007,
print (released)
elif choice=="a":
print (released)
elif choice=="d":
del released["iphone"]
print (released)
elif choice=="l":
print (len(released))
elif choice=="f":
break
else:
elif choice=="g":
elif choice=="r":
elif choice=="s":
else:
OUTPUT:
Menu
(L)ength of dictionary
(Q)uit
>>> c
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone
4S': 2011, 'iphone 5': 2012}
Menu
(L)ength of dictionary
(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
(L)ength of dictionary
OSTL /CSL 405/ Sem- IV Page 28
Computer Engineering / SSJCET, Asangaon
(Q)uit
>>> d
Modified dictionary
{'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone
5': 2012, 'iphone 5S': 2013}
Menu
(L)ength of dictionary
(Q)uit
>>> l
Length of dictionary
Menu
(L)ength of dictionary
(Q)uit
>>> f
Key found
Menu
(L)ength of dictionary
(Q)uit
>>> g
2008
Menu
(L)ength of dictionary
(Q)uit
>>> r
--------------------
Menu
(L)ength of dictionary
(Q)uit
>>> s
iphone 4 2010
iphone 5 2012
iphone 3G 2008
iphone 4S 2011
iphone 5S 2013
Menu
(L)ength of dictionary
(Q)uit
>>> q
CONCLUSION:
EXPERIMENT NO: 9
THEORY:
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:
class Person:
#defining constructor
self.name = personName
self.age = personAge
def showName(self):
print(self.name)
def showAge(self):
print(self.age)
self.studentId = studentId
def getId(self):
return self.studentId
Student.__init__(self, id)
resident1.showName()
print(resident1.getId())
Output:
John
102
CONCLUSION:
EXPERIMENT NO: 10
AIM: Write a python program to demonstrate exception handling using try with
except and finally.
THEORY:
Overview
In this post we will cover how Python handles errors with exceptions.
What is an Exception?
Exception Errors
IOError
ImportError
ValueError
Raised when a built-in operation or function receives an argument that has the
KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or Delete)
EOFError
The error handling is done through the use of exceptions that are caught in try
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:
try:
finally:
fob.close()
except IOError:
try:
if a <= 0:
print(ve)
OUTPUT:
CONCLUSION:
EXPERIMENT NO: 11
AIM: Create a package and module for data structure: Queue and Stack.
THEORY:
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.
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.
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).
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.
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.
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.
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.
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.
PROGRAM/SOURCE CODE:
import queue
#..................................................
#Queue program
#..................................................
print ("_________________________________________")
print ("_________________________________________")
L = queue.Queue(maxsize=6)
# of the Queue
print(L.qsize())
L.put(5)
L.put(9)
L.put(1)
L.put(7)
# Queue
L.put(9)
L.put(10)
print(L.get())
print(L.get())
print(L.get())
# Queue
print(L.get())
print(L.get())
print(L.get())
# print(L.get())
#..................................................
OSTL /CSL 405/ Sem- IV Page 42
Computer Engineering / SSJCET, Asangaon
#Stack program
#..................................................
print ("_________________________________________")
print ("_________________________________________")
S = queue.LifoQueue(maxsize=6)
# the Queue
print(S.qsize())
# same as Queue
S.put(5)
S.put(9)
S.put(1)
S.put(7)
S.put(9)
S.put(10)
# of Queue
print(S.get())
print(S.get())
print(S.get())
print(S.get())
print(S.get())
print(S.get())
OUTPUT:
_________________________________________
Implementing Queue
_________________________________________
Full: False
Full: True
Empty: False
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.
EXPERIMENT NO: 12
AIM: Creation of simple socket for basic information exchange between server &
client
THEORY:
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.
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.
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
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.
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.
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.
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
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():
host = socket.gethostname()
server_socket.listen(2)
while True:
# receive data stream. it won't accept data packet greater than 1024 bytes
data = conn.recv(1024).decode()
if not data:
break
if __name__ == '__main__':
server_program()
socket_client.py
import socket
def client_program():
if __name__ == '__main__':
client_program()
OUTPUT:
$ python3.6 socket_server.py
-> Hello
-> Good
………………………………………………………………………………………
$ python3.6 socket_client.py
-> Hi
-> Awesome!
-> Bye
CONCLUSION:
Thus we have studied a Creation of simple socket for basic information exchange
between server & client
EXPERIMENT NO: 13
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 −
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
print various values. Similarly there are various other functions or sometime called
sub-routines, which can be used for various other functionalities.
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.
PROGRAM/SOURCE CODE:
#!/usr/bin/perl
# create a simple array
@coins = ("Quarter","Dime","Nickel");
print "1. \@coins = @coins\n";
OUTPUT:
CONCLUSION:
EXPERIMENT NO: 14
THEORY:
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.
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:
#!/usr/bin/perl
$to = '[email protected]';
$from = '[email protected]';
# Email Header
# Email Body
close(MAIL);
#!/usr/bin/perl
$to = '[email protected]';
$from = '[email protected]';
# Email Header
# Email Body
close(MAIL);
CONCLUSION: