Python Lab Manual
Python Lab Manual
Python Lab Manual
Exp. Corresponding
Title of experiment
No. CO
1. Demonstrate the working of ‘id’ and ‘type’ functions.
C 220.1
22. Write a program to check if a number is Odd or even. Take input C 220.2
From user.
23. Write a program to check that a given year is Leap Year or not. C 220.2
INTRODUCTION
Python is a language with a simple syntax, and a powerful set of libraries. It is an interpreted
language, with a rich programming environment, including a robust debugger and profiler. While
it is easy for beginners to learn, it is widely used in many scientific areas for data exploration.
This course is an introduction to the Python programming language for students without prior
programming experience. We cover data types, control flow, object-oriented programming, and
graphical user interface-driven applications. The examples and problems used in this course are
drawn from diverse areas such as text processing, simple graphics creation and image
manipulation, HTML and web programming, and genomics.
1. Learn basic programming constructs –data types, decision structures, control structures in
python
2. Know how to use libraries for string manipulation and user-defined functions.
3. Learn to use in-built data structures in python – Lists, Tuples, Dictionary and
File handling.
4. Learn the fundamental principles of Object-Oriented Programming
5. Solve problems through application of OO concepts and using Files/database
Use Python Shell (using command line) and IDLE – Interactive development environment.
To evaluate expression.
To create a script.
Using IDLE
IDLE is the standard Python development environment. Its name is an acronym of "Integrated
DeveLopment Environment". It works well on both Unix and Windows platforms.
It has a Python shell window, which gives you access to the Python interactive mode. It also has
a file editor that lets you create and edit existing Python source files.
During the following discussion of IDLE's features, instead of passively reading along, you
should start IDLE and try to replicate the screenshots.
You can type Python code directly into this shell, at the '>>>' prompt. Whenever you enter
a complete code fragment, it will be executed. For instance, typing:
>>> print "hello world"
PREFACE
This manual will introduce you to the Python programming language. It’s aimed at beginning
programmers, but even if you’ve written programs before and just want to add Python to your
list of languages, It will get you started.
This practical manual will be helpful for students of Computer Science & Engineering for
understanding the course from the point of view of applied aspects.
Though all the efforts have been made to make this manual error free, yet some errors might
have crept in inadvertently. Suggestions from the readers for the improvement of the manual
are most welcomed
DO’s
DONT’S
1. Know the location of the fire extinguisher and the first aid box and how to use them
in case of an emergency.
4. Do not plug in external devices without scanning them for computer viruses.
MARKS FACULTY
DATE OF EXPT. TITLE OF THE PAGE
S. No AWARDED SIGNATURE
CONDUCTION No EXPERIMENT No.
(20) WITH
REMARK
10
11
Name
Roll No.
Section- Batch
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 16
Department of Computer Science &
INDEX
Experiment Experiment Date of Date of Faculty
No. Name Conduction Submission Signature
THEORY:-
As we can see the function accepts a single parameter and is used to return the identity of an
object. id(object)
This identity has to be unique and constant for this object during the lifetime. Two
objects with non-overlapping lifetimes may have the same id() value. If we relate this to C, then
they are actually the memory address, here in Python it is the unique id. This function is generally
used internally in Python.
Examples:
The output is the identity of the object passed. This is random but when running in the
same program, it generates unique and same identity.
Input : id(1025)
Output : 140365829447504
Output varies with different runs
Input : id("geek")
Output : 139793848214784
str2 = "geek"
print(id(str2))
# Use in Lists
list1 = ["aakash", "priya", "abdul"]
print(id(list1[0]))
print(id(list1[2]))
Example:
print('id of 5 =',id(5))
a=5
print('id of a =',id(a))
b=a
print('id of b =',id(b))
c = 5.0
print('id of c =',id(c))
Python have a built-in method called as type which generally come in handy while figuring out
the type of variable used in the program in the runtime.
The type function returns the datatype of any arbitrary object. The possible types are listed in
the types module. This is useful for helper functions that can handle several types of data.
You can use the constants in the types module to compare types of objects. This is what the info
function does, as you'll see shortly.
VIVA QUESTIONS:
1.What data types are used in Python?
2.What is the difference between functions used in python and C? Are both the same?
EXPERIMENT -2
THEORY:-
Prime numbers: A prime number is a natural number greater than 1 and having no positive
divisor other than 1 and itself.
Composite number: Other natural numbers that are not prime numbers are called composite
numbers.
Here is source code of the Python Program to check if a number is a prime number.
VIVA QUESTIONS:
EXPERIMENT-3
THEORY: The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....
The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms.
This means to say the nth term is the sum of (n-1)th and (n-2)th term.
# first two
terms n1 = 0
n2 = 1
count = 0
VIVA QUESTIONS
EXPERIMENT-4
THEORY:- Like other programming languages, it’s possible to access individual characters of a
string by using array-like indexing syntax. In this we can access each and every element of string
through their index number and the indexing starts from 0. Python does index out of bound
checking.
So, we can obtain the required character using syntax, string_name[index_position]:
The positive index_position denotes the element from the starting(0) and the negative
index shows the index from the end(-1).
EXAMPLE-
# A python program to illustrate slicing in
# Prints 7th
character print x[6]
Slicing in string
We use the slice notation on strings. In this example, we omit the first index to start at
the beginning, and then consume four characters total. We extract the first four letters.
VIVA QUESTIONS
EXPERIMENT-5
OBJECTIVE:-
a. To add 'ing' at the end of a given string (length should be at least 3). If the given string
already ends with 'ing' then add 'ly' instead. If the string length of the given string
is less than 3, leave it unchanged.
Sample String : 'abc' Expected Result :
'abcing' Sample String : 'string' Expected Result
: 'stringly'
b. To get a string from a given string where all occurrences of its first char
have been changed to '$', except the first char itself.
Sample String : 'restart' Expected Result :
def add_string(str1):
length =
len(str1)
if length >
2:
if str1[-3:] ==
'ing':
str1 +=
'ly' else:
str1 +=
'ing' return str1
print(add_string('ab'))
print(add_string('abc'))
print(add_string('string'
))
b. PYTHON CODE:
def change_char(str1):
char = str1[0] length
= len(str1)
str1 = str1.replace(char,
'$') str1 = char + str1[1:]
return str1
print(change_char('restart'
))
VIVA QUESTIONS-
EXPERIMENT-6
OBJECTIVE:-
a. To compute the input. The frequency of the words from the output should output after
sorting the key alphanumerically.
b. Write a program that accepts a comma separated sequence of words as input and prints the
words in a comma-separated sequence after sorting them alphabetically.
a. Python code:
def word_count(str):
counts = dict()
words = str.split()
return counts
print( word_count('the quick brown fox jumps over the lazy dog.'))
b.
items = input("Input comma separated sequence of
words") words = [word for word in items.split(",")]
print(",".join(sorted(list(set(words)))))
VIVA QUESTIONS:
EXPERIMENT-7
OBJECTIVE:- Write a program that accepts a sequence of whitespace separated words as input
and prints the words after removing all duplicate words and sorting them alphanumerically.
THEORY:-
Suppose the following input is supplied to the program:
hello world and practice makes perfect and hello world again
Then, the output should be:
again and hello makes perfect practice world
Hints:
In case of input data being supplied to the question, it should be assumed to be a
console input.
We use set container to remove duplicated data automatically and then use sorted() to sort
the data.
Solution:
s = raw_input()
words = [word for word in s.split(" ")]
print " ".join(sorted(list(set(words))))
# #
# #
VIVA QUESTIONS:
2. Mention what are the rules for local and global variables in Python?
EXPERIMENT-8
list.append()
The method list.append(x) will add an item (x) to the end of a list. We’ll start with a list of
our fish that are dispersed throughout the aquarium.
We just got a new fish into the aquarium today, and we would like to add that fish to our list.
We’ll pass the string of our new fish type, 'flounder' into the list.append() method, and then
print out our modified list to confirm that the item was added.
fish.append('flounder')
print(fish)
Output
['barracuda', 'cod', 'devil ray', 'eel', 'flounder']
Now, we have a list of 5 string items that ends with the item we passed to the .append() function.
List.insert()
The list.insert(i,x) method takes two arguments, with i being the index position you would like to
add an item to, and x being the item itself.
Our aquarium acquired another new fish, an anchovy. You may have noticed that so far the
list fish is in alphabetical order. Because of this, we don’t want to just add the string 'anchovy' to
the end of fishwith the list.append() function. Instead, we’ll use list.insert() to add 'anchovy' to
the beginning of this list at index position 0:
fish.insert(0,'anchovy')
print(fish)
Output
['anchovy', 'barracuda', 'cod', 'devil ray', 'eel', 'flounder']
In this case, we added the string item to the front of the list. Each of the successive items will
now be at a new index number as they have all moved down. Therefore, 'barracuda' will be at
index 1, 'cod' will be at index 2, and 'flounder' — the last item — will be at index 5.
If, at this point, we are bringing a damselfish to the aquarium and we wanted to maintain
alphabetical order based on the list above, we would put the item at
index 3: fish.insert(3,'damselfish').
list.extend()
If we want to combine more than one list, we can use the list.extend(L) method, which takes in
a second list as its argument.
Our aquarium is welcoming four new fish from another aquarium that is closing. We have
these fish together in the list more_fish:
We’ll now add the items from the list more_fish to the list fish and print the list to ensure that
the second list was incorporated:
fish.extend(more_fish)
print(fish)
list.remove()
When we need to remove an item from a list, we’ll use the list.remove(x) method which
removes the first item in a list whose value is equivalent to x.
A group of local research scientists have come to visit the aquarium. They are doing research on the
kissing gourami species of fish. They have requested for us to loan our kissing gourami to
them, so we’d l ike to remove the item from the list to reflect this change:
'kissing gourami'
fish.remove('kissing gourami')
print(fish)
Following the use of the list.remove() method, our list no longer has the 'kissing gourami' item.
VIVA QUESTIONS:
EXPERIMENT-9
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence having each item as a
pair my_dict = dict([(1,'apple'), (2,'ball')])
The difference while using get() is that it returns None instead of KeyError, if the key is not found.
Python code:
my_dict = {'name':'Jack', 'age': 26}
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age')
Dictionary are mutable. We can add new items or change the value of existing items using
assignment operator.
If the key is already present, value gets updated, else a new key: value pair is added to the
dictionary.
Python code:
my_dict = {'name':'Jack', 'age': 26}
# update value
my_dict['age'] = 27
# add item
my_dict['address'] = 'Downtown'
The method, popitem() can be used to remove and return an arbitrary item (key, value) form the
dictionary. All the items can be removed at once using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
Python code:
# create a dictionary
# Output: {2: 4, 3: 9}
print(squares)
# Output: {}
print(squares)
# Throws Error
# print(squares)
VIVA QUESTIONS:-
1. What is Dictionary?
EXPERIMENT-10
OBJECTIVE:-To demonstrate use of tuple, set& related functions
THEORY: In Python programming, a tuple is similar to a list. The difference between the two
is that we cannot change the elements of a tuple once it is assigned whereas in a list, elements
can
be changed.
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.).
Python code:
# empty tuple
# Output: ()
my_tuple = ()
print(my_tuple
)
# nested tuple
# Output: ("mouse", [8, 4, 6], (1, 2, 3))
my_tuple = ("mouse", [8, 4, 6], (1, 2,
3)) print(my_tuple)
my_tuple = 3, 4.6,
"dog" print(my_tuple)
1. Indexing
Python code:
my_tuple = ('p','e','r','m','i','t')
# Output: 'p'
print(my_tuple[0])
# Output: 't'
print(my_tuple[5])
#print(my_tuple[6])
#my_tuple[2.0]
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
# Output: 's'
print(n_tuple[0][3])
2. Deleting a Tuple
Deleting a tuple entirely is possible using the keyword del.
my_tuple = ('p','r','o','g','r','a','m','i','z')
#del my_tuple[3]
VIVA QUESTIONS
1. What is a tuple?
THEORY
Stack is a linear data structure which follows a particular order in which the operations are
performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).
Mainly the following three basic operations are performed in the stack:
Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow
condition.
Pop: Removes an item from the stack. The items are popped in the reversed order in
which they are pushed. If the stack is empty, then it is said to be an Underflow condition.
Peek or Top: Returns top element of stack.
isEmpty: Returns true if stack is empty, else false.
How to understand a stack practically?
There are many real life examples of stack. Consider the simple example of plates stacked over
one another in canteen. The plate which is at the top is the first one to be removed, i.e. the plate
which has been placed at the bottommost position remains in the stack for the longest period of
time. So, it can be simply seen to follow LIFO/FILO order.
EXPERIMENT NO 12
THEORY:- In a Queue data structure, we maintain two pointers, front and rear. The front
points the first item of queue and rear points to last item.
enQueue() This operation adds a new node after rear and moves rear to the next node.
deQueue() This operation removes the front node and moves front to the next node.
VIVA QUESTIONS
c) What is queue and how implementation of queue in c is different from python?
d) Difference between queue and
stack?
EXPERIMENT NO 13
OBJECTIVE :-To read and write from a file
THEORY:- When you’re working with Python, you don’t need to import a library in order to
read and write files. It’s handled natively in the language, albeit in a unique manner.
Python provides inbuilt functions for creating, writing and reading files. There are two types of
files that can be handled in python, normal text files and binary files (written in binary
language,0s and 1s).
Text files: In this type of file, Each line of text is terminated with a special character
called EOL (End of Line), which is the new line character (‘\n’) in python by default.
Binary files: In this type of file, there is no terminator for a line and the data is stored
after converting it into machine understandable binary language.
In this article, we will be focusing on opening, closing, reading and writing data in a text file.
File Access Modes
Access modes govern the type of operations possible in the opened file. It refers to how the file
will be used once its opened. These modes also define the location of the File Handle in the file.
File handle is like a cursor, which defines from where the data has to be read or written in the file.
There are 6 access modes in python.
Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of
the file. If the file does not exists, raises I/O error. This is also the default mode in which
file is opened.
Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at
the beginning of the file. Raises I/O error if the file does not exists.
Write Only (‘w’) : Open the file for writing. For existing file, the data is truncated and
over-written. The handle is positioned at the beginning of the file. Creates the file if the
file does not exists.
Write and Read (‘w+’) : Open the file for reading and writing. For existing file, data is
truncated and over-written. The handle is positioned at the beginning of the file.
Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. The
handle is positioned at the end of the file. The data being written will be inserted at the
end, after the existing data.
Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it
does not exist. The handle is positioned at the end of the file. The data being written will
be inserted at the end, after the existing data.
Opening a File
# Open function to open the file "MyFile1.txt"
# (same directory) in append mode and
file1 = open("MyFile.txt","a")
Closing a file
# Opening and Closing a file "MyFile.txt"
# for object name file1.
file1 = open("MyFile.txt","a")
file1.close()
Writing to a file
There are two ways to write in a file.
1. write() : Inserts the string str1 in a single line in the text
2. writelines() : For a list of string elements, each string is inserted in the text file.Used to
insert multiple strings at a single time.
file1 = open("myfile.txt","r+")
file1.seek(0)
file1.seek(0)
# readlines function
print "Output of Readlines function is "
print file1.readlines()
print
file1.close()
VIVA QUESTIONS
1. What is write command?
2. What is the difference between write and append?
EXPERIMENT NO 14
THEORY:- To add something at the end. For example, you can append one file to another or
you can append a field to a record. Do not confuse append with insert. Appendalways means to
add at the end. Insert means to add in between.
# Append-adds at last
file1 = open("myfile.txt","a")#append mode
file1.write("Today \n")
file1.close()
file1 = open("myfile.txt","r")
print "Output of Readlines after appending"
print file1.readlines()
print
file1.close()
# Write-Overwrites
file1 = open("myfile.txt","w")#write mode
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt","r")
print "Output of Readlines after writing"
print file1.readlines()
print
file1.close()
VIVA QUESTIONS
1. What is the difference write and read mode?
2.What are the symbols used for the mode?
EXPERIMENT NO 15
THEORY: Like function definitions begin with the keyword def, in Python, we define a class
using the keyword class.The first string is called docstring and has a brief description about the
class. Although not mandatory, this is recommended.
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
class MyClass:
"This is my second class"
a = 10
def func(self):
print('Hello')
# Output: 10
print(MyClass.a)
It can also be used to create new object instances (instantiation) of that class. The procedure to
create an object is similar to a function call.
>>> ob = MyClass()
class MyClass:
"This is my second
class" a = 10
def func(self):
print('Hello')
print(ob.func)
VIVA QUESTIONS
1. What is class?How to define class in python?
2. What is object?How to use it in python?
EXPERIMENT NO 16
class C(object):
@classmethod
def fun(cls, arg1, arg2, ...):
....
fun: function that needs to be converted into a class method
returns: a class method for function.
A class method is a method which is bound to the class and not the object of the class.
They have the access to the state of the class as it takes a class parameter that points to the
class and not the object instance.
It can modify a class state that would apply across all the instances of the class. For
example it can modify a class variable that will be applicable to all the instances.
Static Method
A static method does not receive an implicit first argument.
class C(object):
@staticmethod
def fun(arg1, arg2, ...):
...
returns: a static method for function fun.
# Python program to demonstrate
# use of class method and static
method. from datetime import date
class Person:
def init (self, name, age):
self.name = name
self.age = age
print person1.age
print person2.age
VIVA QUESTIONS
1. What is static method in java?
2. What is auto and static in C?
EXPERIMENT NO. 17
THEORY
Class functions that begins with double underscore ( ) are called special functions as they have
special meaning.
One particular interest is the init () function. This special function gets called whenever a new
object of that class is instantiated.
This type of function is also called constructors in Object Oriented Programming (OOP). We
normally use it to initialize all the variables.
class ComplexNumber:
def init (self,r = 0,i = 0):
self.real = r
self.imag = i
def getData(self):
print("{0}+{1}j".format(self.real,self.imag))
# Create a new ComplexNumber
object c1 = ComplexNumber(2,3)
# Call getData() function
# Output: 2+3j
c1.getData()
# Create another ComplexNumber object
# and create a new attribute 'attr'
c2 = ComplexNumber(5)
c2.attr = 10
# Output: (5, 0, 10)
print((c2.real, c2.imag, c2.attr))
VIVA QUESTIONS
EXPERIMENT NO 18
It refers to defining a new class with little or no modification to an existing class. The new class is
called derived (or child) class and the one from which it inherits is called the base (or parent)
class.
SYNTAX
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
Derived class inherits features from the base class, adding new features to it. This results into re-
usability of code.
class Polygon:
def init (self, no_of_sides):
self.n = no_of_sides
self.sides = [0 for i in range(no_of_sides)]
def inputSides(self):
self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]
def dispSides(self):
for i in range(self.n):
print("Side",i+1,"is",self.sides[i])
This class has data attributes to store the number of sides, n and magnitude of each side as a list,
sides.
Method inputSides() takes in magnitude of each side and similarly, dispSides() will display these
properly.
A triangle is a polygon with 3 sides. So, we can created a class called Triangle which inherits from
Polygon. This makes all the attributes available in class Polygon readily available in Triangle. We
don't need to define them again (code re-usability). Triangle is defined as follows.
class Triangle(Polygon):
def init (self):
Polygon. init (self,3)
def findArea(self):
a, b, c = self.sides
# calculate the semi-
perimeter s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
VIVA QUESTIONS
1. What is Polymorphism?
class Student:
def init (self, name, student_number):
self.name = name
self.student_number = student_number
self.classes = []
class Department:
def init (self, name, department_code):
self.name = name
self.department_code = department_code
self.courses = {}
class Course:
def init (self, description, course_code, credits, department):
self.description = description
self.course_code = course_code
self.credits = credits
self.department = department
self.department.add_course(self)
self.runnings = []
VIVA QUESTIONS
1. What is aggregation?
2. What is generalization?
EXPERIMENT NO 20
OBJECTIVE:- To create a small GUI application for insert, update and delete in a table using
Oracle as backend and front end for creating form
After installing the MySQL Python connector, you need to test it to make sure that it is working
correctly and you are able to connect to MySQL database server without any issues. To verify the
installation, you use the following steps:
Open Python command line
Type the following code
>>> import mysql.connector
>>> mysql.connector.connect(host='localhost',database='mysql',user='root',password='')
1
2
>>> import mysql.connector
>>> mysql.connector.connect(host='localhost',database='mysql',user='root',password='')
If the output is shown as below, you have been successfully installing the MySQL Python
connector in your system.
<mysql.connector.connection.MySQLConnection object at
0x0187AE50> 1
<mysql.connector.connection.MySQLConnection object at 0x0187AE50>
EXPERIMENT NO 21
OBJECTIVE:- Write a program to compute area and circumference of a triangle. Take input from
user.
Python Code :
Area_of_Triangle(6, 7, 8)
VIVA QUESTIONS
2. What is value of S?
EXPERIMENT NO 22
OBJECTIVE:- Write a program to check if a number is Odd or even. Take input from
user.
THEORY : If the number is divisible by 2 , that number is called even number, else the number
is odd.
Python Code :
VIVA QUESTIONS
EXPERIMENT NO 23
THEORY : If the year is divisible by 4, 100 and 400 then that year is a leap year.
Python Code :
year = 2000
# To get year (integer input) from the user
# year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
VIVA QUESTIONS :