Rcs454: Python Language Programming LAB: Write A Python Program To
Rcs454: Python Language Programming LAB: Write A Python Program To
Rcs454: Python Language Programming LAB: Write A Python Program To
LAB
Write a Python program to: -
1. Demonstrate the working of ‘id’ and ‘type’ functions
2. To find all prime numbers within a given range.
3. To print ‘n terms of Fibonacci series using iteration.
4. To demonstrate use of slicing in string
5. 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.
6. a. To compute the frequency of the words from the input. 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.
7. 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.
8. To demonstrate use of list & related functions
9. To demonstrate use of Dictionary& related functions
10. To demonstrate use of tuple, set& related functions
11. To implement stack using list
12. To implement queue using list
13. To read and write from a file
14. To copy a file
15. To demonstrate working of classes and objects
16. To demonstrate class method & static method
17. To demonstrate constructors
18. To demonstrate inheritance
19. To demonstrate aggregation/composition
20. To create a small GUI application for insert, update and delete in a table using Oracle as backend
and front end for creating form
The lab experiments for this course have to ensure that the following concepts of PYTHON
LANGUAGE are covered during lab classes:
Installing Python; basic syntax, interactive shell, editing, saving, and running a script, the concept of
data types; variables, assignments; immutable variables; numerical types; arithmetic operators and
expressions; reading input from console, writing to console, comments in the program; understanding
error messages; Conditions, Boolean logic, logical operators; ranges; Control statements: if-else,
loops (for, while);
String manipulations: subscript operator, indexing, slicing a string; other functions on strings: string
module, strings and number system, format functions: converting strings to numbers and vice versa.
Binary, octal, hexadecimal numbers
Lists, tuples, sets, and dictionaries: basic list operators, replacing, inserting, removing an element;
searching and sorting lists; dictionary literals, adding and removing keys, accessing and replacing
values; traversing dictionaries, Array in Python
Regular Expressions: re modules, match function, search function, modifiers and patterns
Design with functions: hiding redundancy, complexity; arguments and return values; formal vs actual
arguments, named arguments. Program structure and design. Recursive functions, scope and global
statements, Lambda expressions, Importing Modules, math Module & Random Modules, creating
own module.
Exception Handling: Exceptions, except clause, try and finally clause user defined exceptions File
Handling: manipulating files and directories, os and sys modules; text files: reading/writing text and
numbers from/to a file;
Simple Graphics: “turtle” module; simple 2d drawing - colors, shapes; digital images, image file
formats. Graphical user interfaces: event-driven programming paradigm; tkinter module, creating
simple GUI; buttons, labels, entry fields, dialogs; widget attributes - sizes, fonts, colors layouts,
nested frames.
Database: cx_ Oracle module, Connections, Executing Queries, calling procedure and functions,
Using GUI to access Database.
Object Oriented Programming: Concept of OOP: Abstraction, Encapsulation, Inheritance, and
Polymorphism in Python, classes, objects, attributes and methods; defining classes; design with
classes, constructors and destructors, inheritance, polymorphism, operator overloading (_eq_, _str_,
etc); abstract classes; aggregation and composition.
Reference books:
1. John M. Sewart, “Python for Scientist”, Cambridge Universities Press.
2. Reema Thareja, “Python Programming” Oxford Higher Education.
3. Robert Sedgewick, Kevin Wayne, Robert Dondero, “Introduction to Programming in Python”
Pearson
4. Mrak Litz, “ Learning Python”,O’ Reilly
5. Mark Pilgrim, “Dive into Python”, Apress
6. James L. Young, “Python made Simple and Practical”, Kindle Edition (paperback)
7. Y. Daniel Liang “Introduction to Programming using Python” Pearson
EXPERIMENT 1
THEORY:-
As we can see the function accepts a single parameter and is used to return the identity of an
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]))
The id() function returns identity of the object. This is an integer which is unique for the given
object and remains constant during its lifetime.
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.
>>> type(1)
<type 'int'>
>>> li = []
>>> type(li)
<type 'list'>
>>> type(odbchelper)
<type 'module'>
True
type takes anything -- and I mean anything -- and returns its datatype. Integers, strings,
lists, dictionaries, tuples, functions, classes, modules, even types are acceptable.
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:
2.What is the difference between functions used in python and C?Are both the same?
EXPERIMENT -2
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.
for a in range(2,r+1):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print(a)
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, ……..
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.
def fibonacci(n):
a=0
b=1
for i in range(0, n):
temp = a
a=b
b = temp + b
return a
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 strings
x = "Geeks at work"
Strings. 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.
word = "something"
# Get first four characters.
part = word[:4]
print(part)
Copy. With slicing, we can copy sequences like lists. We assign a new list variable to a
slice with no specified start or stop values. So the slice copies the entire list and returns it.
To extract substring from the whole string then then we use the syntax like
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'
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 : 'resta$t'
a.Python Code:
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)
return str1
print(change_char('restart'))
VIVA QUESTIONS-
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:
EXPERIEMNT-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:-
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
THEORY:- Python has a number of built-in data structures, including lists. Data structures
provide us with a way to organize and store data, and we can use built-in methods to retrieve or
manipulate that data.
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.
fish = ['barracuda','cod','devil ray','eel']
This list is comprised of 4 string items, and their index numbers range from 'barracuda' at 0
to 'eel' at index 3.
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 like to remove the 'kissing gourami' item from the list to reflect this change:
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:
THEORY:- Python dictionary is an unordered collection of items. While other compound data
types have only value as an element, a dictionary has a key: value pair.
Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
An item has a key and the corresponding value expressed as a pair, key: value.
While values can be of any data type and can repeat, keys must be of immutable type
(string,number or tuple with immutable elements) and must be unique.
# empty dictionary
my_dict = {}
# using dict()
The difference while using get() is that it returns None instead of KeyError, if the key is not
found.
Python code:
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# my_dict.get('address')
# my_dict['address']
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['age'] = 27
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
print(my_dict)
We can remove a particular item in a dictionary by using the method pop(). This method
removes as item with the provided key and returns the value.
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
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
# Output: {2: 4, 3: 9}
print(squares)
# Output: {}
print(squares)
# delete the dictionary itself
del squares
# Throws Error
# print(squares)
VIVA QUESTIONS:-
1.What is Dictionary?
2. When does a dictionary is used instead of a list?
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)
# tuple having integers
# Output: (1, 2, 3)
my_tuple = (1, 2, 3)
print(my_tuple)
print(my_tuple)
# nested tuple
print(my_tuple)
print(my_tuple)
# tuple unpacking is also possible
# Output:
#3
# 4.6
# dog
a, b, c = my_tuple
print(a)
print(b)
print(c)
There are various ways in which we can access the elements of a 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])
# index must be in range
#print(my_tuple[6])
#my_tuple[2.0]
# nested tuple
# nested index
# Output: 's'
print(n_tuple[0][3])
# nested index
# Output: 4
print(n_tuple[1][1])
2. Deleting a Tuple
my_tuple = ('p','r','o','g','r','a','m','i','z')
#del my_tuple[3]
del my_tuple
my_tuple
VIVA QUESTIONS
1.What is a tuple?
EXPERIMENT NO 11
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.
return stack.pop()
VIVA QUESTIONS
a) What is Stack and how implementation of Stack in c is different from python?
b) Difference between queue and stack?
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
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 file.
File_object. write (str1)
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.
File_object.writelines(L) for L = [str1, str2, str3]
file1 = open("myfile.txt","r+")
file1.seek(0)
file1.seek(0)
VIVA QUESTIONS
1.what is write command?
2.What is the difference between write and append?
EXPERIMENT NO 14
OBJECTIVE: Appending to a file
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
OBJECTIVE :-To demonstrate working of classes and objects
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)
We saw that the class object could be used to access different attributes.
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')
# create a new MyClass
ob = MyClass()
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
OBJECTIVE :To demonstrate class method & static method
THEORY:-
Class Method
The @classmethod decorator, is a builtin function decorator that is an expression that gets
evaluated after your function is defined. The result of that evaluation shadows your function
definition.
A class method receives the class as implicit first argument, just like an instance method receives
the instance
class C(object):
@classmethod
....
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
OBJECTIVE :-To demonstrate constructors
THEORY
Class functions that begins with double underscore (__) are called special functions as they have
special meaning.
Of 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:
self.real = r
self.imag = i
def getData(self):
print("{0}+{1}j".format(self.real,self.imag))
c1 = ComplexNumber(2,3)
# Output: 2+3j
c1.getData()
c2 = ComplexNumber(5)
c2.attr = 10
# Output: (5, 0, 10)
c1.attr
VIVA QUESTIONS
EXPERIMENT NO 18
OBJECTIVE :-To demonstrate inheritance
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?
2. What is multiple and multilevel inheritance?
EXPERIMENT NO 19
OBJECTIVE :-To demonstrate aggregation/composition
THEORY:- Composition. Composition is a specialized form of aggregation in which if the
parent object is destroyed, the child objects would cease to exist. It is actually a strong type
of aggregation and is also referred to as a "death" relationship. According to some formal
definitions the term composition implies that the two objects are quite strongly linked – one
object can be thought of as belonging exclusively to the other object. If the owner object ceases
to exist, the owned object will probably cease to exist as well. If the link between two objects is
weaker, and neither object has exclusive ownership of the other, it can also be
called aggregation.
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 = {}
self.runnings = []
class CourseRunning:
def __init__(self, course, year):
self.course = course
self.year = year
self.students = []
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
Viva-Voce Questions
Experiment-1
1. What is the difference between the strings and the words of a language?
2. What is the difference between L+ and L*.
Experiment-2
1. What is Non-Determinism and Determinism and what is the difference between them?
2. Finite state machine recognize which type of grammar.
Experiment-3
1. Differentiate between DFA and NFA?
2. If a language can be expressed in the form of FA than why it is needed to use NFA?
Experiment-4
1. What is the difference between concatenation and intersection of two FA’s?
2. What are the basic limitations of Finite automata machine?
Experiment-5
1. Define Regular Expression?
2. Explain the Arden’s Theorem.
Experiment-6
1. Differentiate between (a, b) and (a + b)?
2. Find the regular expression for the language L= {w € (0, 1)*: w has no pair of
consecutive zero’s}.
Experiment-7
1. State the significance of Pumping Lemma theorem.
2. What are the decision properties of regular language?
Experiment-8
1. What is the corresponding FA for RE =aa((a+b)(a+b))*.
2. Which principle is an example of Pumping lemma theorem?
Experiment-9
1. Differentiate between Mealy and Moore machine.
2. How Moore and Mealy machine works in Computer Memory what is their importance in
Computing?
Experiment-10
1. What is the use of push down automata in computing?
2. What is difference between PUSH DOWN STACK and PUSH DOWN STORE?
Experiment-11
1. Explain halting problem in Turing machine.
2. What do you understand by recursively enumerable languages?
Experiment-12
1. What is multi tape Turing machine?
2. Which type of Turing machine is more powerful?
Experiment-13
1. Production Rule: aAb->agb belongs to which of the following category of language.
2. How we can distinguish between “CFG” and “CNF”.
Experiment-14
1. What do you mean by ambiguity in grammar?
2. Find the leftmost derivation for the word abba in the grammar:
S AA
A aB
B bB/€
Experiment-15
1. What do you mean by Unit production?
2. What is the difference between Context free languages and regular languages?