0% found this document useful (0 votes)
67 views

Python Lab Manual 1

Python

Uploaded by

dasthaya04
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Python Lab Manual 1

Python

Uploaded by

dasthaya04
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

LAB MANUAL

SUBJECT NAME- PYTHON LAB

SUBJECT CODE- CS506

CLASS/SECTION- CSE

YEAR/SEMESTER- 3RD YEAR / 5TH SEM

SUBMITTED TO: SUBMITTED BY:


MS. SALONI GAUTAM
ASST. PROFESSOR
DEPTT. OF CSE
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

SESSION: JULY – DEC 2023

LAB MANUAL

SEMESTER-V

SUBJECT- PYTHON LAB

SUBJECT CODE – CS-506

BRANCH - CSE
CONTENTS

1. Vision Mission of the Institute


2. Vision Mission of the Department
3. PEOs
4. POs
5. COs
6. Content beyond Syllabus. ( if any)
7. Laboratory Regulations and Safety Rules
8. Index
9. Experiments

Vision of the Institute

To be the fountainhead of novel ideas & innovations in science & technology &
persist to be a foundation of pride for all Indians.

Mission of the Institute

● To provide value based broad Engineering, Technology and Science where


education in students are urged to develop their professional skills.

● To inculcate dedication, hard work, sincerity, integrity and ethics in building up


overall professional personality of our student and faculty.

● To inculcate a spirit of entrepreneurship and innovation in passing out students.

● To instigate sponsored research and provide consultancy services in technical,


educational and industrial areas.

Vision of the Department

Attaining global recognition in computer science and engineering education,


research and training to meet the growing needs of the industry and society.
Mission of the Department

Provide quality undergraduate and postgraduate education, in both the


theoretical and applied foundations of computer science, and train students
to effectively apply this education to solve real-world problems, thus
amplifying their potential for lifelong high-quality careers.

Program Education Objectives (PEOs)


1. To prepare students for successful careers in software industry that meet
the needs of Indian and multinational companies.
2. To develop the skills among students to analyze real world problem &
implement with computer engineering solution and in multidisciplinary
projects.
3. To provide students with solid foundation in mathematical, scientific and
engineering fundamentals to solve engineering problems and required to
pursue higher studies.
4. To develop the ability to work with the core competence of computer
science & engineering i.e. software engineering, hardware structure &
networking concepts so that one can find feasible solution to real world
problems.
5. To inseminate in students professional and ethical attitude, effective
communication skills, team work skills, multidisciplinary approach, and
an ability to relate engineering issues to broader social context.
6. To motivate students perseverance for lifelong learning and to introduce
them to professional ethics and codes of professional practice.

Program Outcomes (Pos)


a. Graduates will demonstrate knowledge of mathematics, science and allied
engineering in computer science & engineering.
b. Graduates will demonstrate ability to analysis, design and implement the
problems as per user requirements and specification.
c. Graduates will possess strong fundamental concepts on database technologies,
operating system, compiler design, networking, data structure, software
engineering.
d. Graduates will be able to demonstrate with excellent programming, analytical,
logical and problem solving skills.
e. Graduates will demonstrate and ability to visualize and work on laboratory and
multidisciplinary tasks.
f. Graduates will demonstrate skills to use modern engineering tools, softwares
and equipment to analyze problems.
g. Graduates will posses leadership and management skills with best professional
ethical practices.
h. Graduates will be able to communicate effectively in both verbal and written
form.
i. Graduates will have the confidence to apply computer science and engineering
solution for the welfare of human being.
j. Graduates will enhance their self confidence and capable of being a kaizen.
k. Graduates will have ability for life long learning and acquire capability to
succeed in examination like GATE, GRE, IES etc.

Course Outcomes (Cos)


CO nos. Statement of CO Blooms
Taxonomy
Level
Describe about simple computational problems using Python
CO1 BT-1
programs.
Use of Python lists, tuples and dictionaries for representing
CO2 BT-3
compound data.

CO3 Solve problems using conditionals and loops in Python. BT-3

Explain about Object oriented programming and uses of


CO4 BT-2
exception Handling

CO5 Describe Python programs using files. BT-1

Laboratory Regulations and Safety Rules

1. Without Prior permission do not enter into the Laboratory.


2. While entering into the LAB students should wear their ID cards.
3. The Students should come with proper uniform.
4. Student should not use mobile phone inside the laboratory.
5. Students should sign in the LOGIN REGISTER before entering into the
laboratory.
6. Students should come with observation and record note book to the
laboratory.
7. Do not change any computer setting.
8. Students should maintain silence inside the laboratory.
9. After completing the laboratory exercise, make sure to SHUTDOWN the
system properly.

Swami Vivekanand College of Engineering

INDEX

Marks Obtained
Date of Date of Signature Signature
S. No. Experiment Name Experiment Submission LW(10 PQ(10 of Student of Fcaulty
marks marks)
Write a program for
1. literals, constants, datatype,
i/o (CO1)
To create a program for
2. list, tuples and dictionary
(CO2)
To write a program to find
mean, median, mode for
3. the given set of numbers in
a list.(CO1)
To Write a program to find
4. the first n prime numbers
(CO3)
Write a Program for
checking whether the given
5. number is an even number
or not (CO3)
Write a program to find the
6. square root of a number
(CO3)
To Write a program to find
7. the exponentiation (Power
of a number) (CO3)
To write a program to print
8. Fibonacci Series (CO3)
To write a program to show
9. Inheritance (CO4)
To achieve functional
10. Polymorphism (CO4)

Write a program to print


11. each line of a file in reverse
order (C05)

INTRODUCTION TO PYTHON
Introduction

Python is a high-level, general-purpose, interpreted, interactive, object-oriented dynamic


programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl,
Python source code is also available under the GNU General Public License (GPL). Python is
named after a TV Show called ‘Monty Python’s Flying Circus’ and not after Python-the snake.

Python 3.0 was released in 2008. Although this version is supposed to be backward
incompatibles, later on many of its important features have been back ported to be compatible
with version 2.7

Installing Python

Virtually all modern programming languages make us of an IDE, or Integrated


Development Environment, which allows the creation, editing, testing, and saving of programs
and modules.

For Python programming you need a working Python installation and a text editor.
Python comes with its own editor, IDLE, which is quite nice and totally sufficient for the
beginning.

The Python download page is http://www.python.org/download. The most recent version


is Python 3.5.3 (as of January 2017);
Windows users

Download the appropriate Windows installer (the x86 MSI installer, if you do not have a
64-bit AMD or Intel chip). Start the installer by double-clicking it and follow the prompts.

See https://docs.python.org/3/using/windows.html#installing-python for information.


Mac users

Starting from Mac OS X Tiger, Python ships by default with the operating system, but
you will need to update to Python 3 until OS X starts including Python 3 (check the version by
starting python3 in a command line terminal). Also IDLE (the Python editor) might be missing
in the standard installation. If you want to (re-)install Python, get the MacOS installer from the
Python download sit
Linux, BSD, and UNIX users

You are probably lucky and Python is already installed on your machine. To test it type
python3 on a command line. If you see something like what is shown in the following section,
you are set.

IDLE may need to be installed separately, from its own package such as idle3 or as part
of python-tools.

If you have to install Python, first try to use the operating system's package manager or
go to the repository where your packages are available and get Python 3. Python 3.0 was
released in December 2008; all distributions should have Python 3 available, so you may not
need to compile it from scratch. Ubuntu and Fedora do have Python 3 binary packages
available, but they are not yet the default, so they need to be installed specially.

Roughly, here are the steps to compile Python from source code in Unix (If these totally
don't make sense, you may want to read another introduction to *nix, such as Introduction to
Linux):

Download the .tgz file (use your Web browser to get the gzipped tar file
from https://www.python.org/downloads/release/python-343)

• Uncompress the tar file (put in the correct path to where you downloaded it):

$ tar -xvzf ~/Download/Python-3.4.3.tgz ...

list of files as they are uncompressed

• Change to the directory and tell the computer to compile and install the program

cd Python-3.4/
$ ./configure --prefix=$HOME/python3_install

... lots of output. Watch for error messages here ...

$ make

... even more output. Hopefully no error messages ...

$ make install

• Add Python 3 to your path. You can test it first by specifying the full path. You
should add $HOME/python3_install/bin to your PATH bash variable

$ ~/python3_install/bin/python3

Python 3.4.3 (... size and date information ...)

[GCC 4.5.2] on linux2

Type "help", "copyright", "credits" or "license" for more information. >>>

The above commands will install Python 3 to your home directory, which is probably what
you want, but if you skip the --prefix=$HOME/python3_install, it will install it to /usr/local. If
you want to use the IDLE graphical code editor, you need to make sure that the tk and tcl
libraries, together with their development files, are installed on the system. You will get a
warning during the make phase if these are not available.

Configuring your PATH environment variable

The PATH environment variable is a list of folders, separated by semicolons, in which


Windows will look for a program whenever you try to execute one by typing its name at a
Command Prompt. You can see the current value of your PATH by typing this command at a
Command Prompt:

echo %PATH%

The easiest way to permanently change environment variables is to bring up the built-in
environment variable editor in Windows. How you get to this editor is slightly different on
different versions of Windows.

On Windows 8 or Windows 10:

Press the Windows key and type Control Panel to locate the Windows Control Panel.
Once you've opened the Control Panel, select View by: Large Icons, then click on System. In the
window that pops up, click the Advanced System Settings link, then click the Environment
Variables... button.
On Windows 7 or Vista:

Click the Start button in the lower-left corner of the screen, move your mouse over
Computer, right-click, and select Properties from the pop-up menu. Click the Advanced System
Settings link, then click the Environment Variables... button.
On Windows XP:

Right-click the My Computer icon on your desktop and select Properties. Select the
Advanced tab, then click the Environment Variables... button.

Once you've brought up the environment variable editor, you'll do the same thing
regardless of which version of Windows you're running. Under System Variables in the bottom
half of the editor, find a variable called PATH. If there is is one, select it and click Edit....
Assuming your Python root is C:\Python34, add these two folders to your path (and make sure you
get the semicolons right; there should be a semicolon between each folder in the list):

:\Python34

C:\Python34\Scripts

Python programming – modes

Python has two basic modes: normal and interactive. The normal mode is the mode
where the scripted and finished .py files are run in the Python interpreter. Interactive mode is a
command line shell which gives immediate feedback for each statement, while running
previously fed statements in active memory. As new lines are fed into the interpreter, the fed
program is evaluated both in part and in whole.

Interactive mode is a good way to play around and try variations on syntax.

On macOS or linux, open a terminal and simply type "python". On Windows, bring up
the command prompt and type "py", or start an interactive Python session by selecting "Python
(command line)", "IDLE", or similar program from the task bar / app menu. IDLE is a GUI
which includes both an interactive mode and options to edit and run files. Python should print
something like this:

$ python

Python 3.0b3 (r30b3:66303, Sep 8 2008, 14:01:02) [MSC v.1500 32 bit

(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>>

The >>> is Python's way of telling you that you are in interactive mode. In interactive mode
what you type is immediately run. Try typing 1+1 in. Python will respond with 2. Interactive
mode allows you to test out and see what Python will do. If you ever feel the need to play with
new Python statements, go into interactive mode and try them out. A sample interactive session:
>>>5

>>>print(5*7)

35

>>>"hello" * 4

'hellohellohellohello'

>>>"hello".__class__

<type 'str'>

However, you need to be careful in the interactive environment to avoid confusion.

For example, the following is a valid Python script:

if 1:

print("True")

print("Done")

If you try to enter this as written in the interactive environment, you might be surprised by
the result:

>>> if 1:

... print("True")

... print("Done")

File "<stdin>", line 3

print("Done")

SyntaxError: invalid syntax


What the interpreter is saying is that the indentation of the second print was unexpected.
You should have entered a blank line to end the first (i.e., "if") statement, before you started
writing the next print statement. For example, you should have entered the statements as though
they were written:

if 1:

print("True")

print("Done")

Which would have resulted in the following:

>>> if 1:

... print("True")

...

True

>>> print("Done")

Done

>>>

Interactive mode

Instead of Python exiting when the program is finished, you can use the -i flag to
start an interactive session. This can be very useful for debugging and prototyping.

python -i hello.p
Experiment.No.1

Write a program for literals, constants, datatype, i/o (CO1)

LITERALS:

Python comes with some built-in objects. Some are used so often that Python has a quick way to

make these objects, called literals. The literals include the string, unicode string, integer, float,

long, list, tuple and dictionary types

Program:

a = 0b1010 #Binary Literals

b = 100 #Decimal Literal

c = 0o310 #Octal Literal

d = 0x12c #Hexadecimal Literal

#Float Literal

float_1 = 10.5

float_2 = 1.5e2

#Complex Literal

x = 3.14j

print(a, b, c, d)

print(float_1, float_2)

print(x, x.imag, x.real)


Output:

10 100 200 300

10.5 150.0

3.14j 3.14 0.0

Constants:

A constant is a type of variable whose value cannot be changed. It is helpful to think of constants

as containers that hold information which cannot be changed later

Program:

Create a constant.py

PI = 3.14

GRAVITY = 9.8

Create a main.py

import constant

print(constant.PI)

print(constant.GRAVITY)
Output:

3.14

9.8

Datatypes:

Basic Data Types in Python

● Integers.

● Floating-Point Numbers.

● Complex Numbers.

● Strings. Escape Sequences in Strings. Raw Strings. Triple-Quoted Strings.

● Boolean Type, Boolean Context, and “Truthiness”

● Built-In Functions. Math. Type Conversion. Iterables and Iterators. Composite Data Type.

Classes, Attributes, and Inheritance.

Input output :

Python Output Using print() function

We use the print() function to output data to the standard output device (screen)

Program:

print('This sentence is output to the screen')


Output: This sentence is output to the screen

a=5

print('The value of a is', a)

Output:

The value of a is 5

Python Input

Up till now, our programs were static. The value of variables were defined or hard coded into the

source code.

To allow flexibility we might want to take the input from the user. In Python, we have

the input() function to allow this.

Program:

>>> num = input('Enter a number: ')

Enter a number: 10

>>> num

'10'
Viva Questions

Q1.What is Python?(CO1)

Ans. Python is a high-level, interpreted, interactive and object-oriented scripting language.


Python is designed to be highly readable. It uses English keywords frequently where as
other languages use punctuation, and it has fewer syntactical constructions than other
languages
Q2.What are the supported data types in Python?(CO1)

Ans. Python has five standard data types −


● Numbers
● String
● List
● Tuple
● Dictionary
Experiment.No.2

To create a program for list, tuples and dictionary (CO2)


1

Introduction

If you need to store a long list of information, which doesn't change over time? Say, for example,
the names of the months of the year. Or maybe a long list of information, that does change over
time? Say, for example, the names of all your cats. You might get new cats, some may die, some
may become your dinner (we should trade recipes!). What about a phone book? For that you
need to do a bit of referencing - you would have a list of names, and attached to each of those
names, a phone number. How would you do that?

The Solution - Lists, Tuples, and Dictionaries


For these three problems, Python uses three different solutions - Tuples, lists, and dictionaries:

● Lists are what they seem - a list of values. Each one of them is numbered, starting from
zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove
values from the list, and add new values to the end. Example: Your many cats' names.

● Tuples are just like lists, but you can't change their values. The values that you give it
first up, are the values that you are stuck with for the rest of the program. Again, each
value is numbered starting from zero, for easy reference. Example: the names of the
months of the year.

● Dictionaries are similar to what their name suggests - a dictionary. In a dictionary, you
have an 'index' of words, and for each of them a definition. In python, the word is called a
'key', and the definition a 'value'. The values in a dictionary aren't numbered - they are
similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of
words, and for each of them a definition. In python, the word is called a 'key', and the
definition a 'value'. The values in a dictionary aren't numbered - they aren't in any specific
order, either - the key does the same thing. You can add, remove, and modify the values
in dictionaries. Example: telephone book.

Program :

1. Program for Lists

my_list = ['p','r','o','b','e']
# Output: p

print(my_list[0])

# Output: o

print(my_list[2])

# Output: e

print(my_list[4])

# Error! Only integer can be used for indexing

# my_list[4.0]

# Nested List

n_list = ["Happy", [2,0,1,5]]

# Nested indexing

# Output: a

print(n_list[0][1])

# Output: 5

print(n_list[1][3])
Output:

2. Program for Tuples

# empty tuple

# Output: ()

my_tuple = ()

print(my_tuple)

# tuple having integers

# Output: (1, 2, 3)

my_tuple = (1, 2, 3)

print(my_tuple)

# tuple with mixed datatypes

# Output: (1, "Hello", 3.4)

my_tuple = (1, "Hello", 3.4)


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)

# tuple can be created without parentheses

# also called tuple packing

# Output: 3, 4.6, "dog"

my_tuple = 3, 4.6, "dog"

print(my_tuple)

# tuple unpacking is also possible

# Output:

#3

# 4.6

# dog

a, b, c = my_tuple

print(a)

print(b)

print(c)
Output:

()

(1, 2, 3)

(1, 'Hello', 3.4)

('mouse', [8, 4, 6], (1, 2, 3))

(3, 4.6, 'dog')

4.6

dog

3. Program for Dictionary

# Creating an empty Dictionary

Dict = {}

print("Empty Dictionary: ")

print(Dict)

# Creating a Dictionary

# with Integer Keys

Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}


print("\nDictionary with the use of Integer Keys: ")

print(Dict)

# Creating a Dictionary

# with Mixed keys

Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}

print("\nDictionary with the use of Mixed Keys: ")

print(Dict)

# Creating a Dictionary

# with dict() method

Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})

print("\nDictionary with the use of dict(): ")

print(Dict)

# Creating a Dictionary

# with each item as a Pair

Dict = dict([(1, 'Geeks'), (2, 'For')])

print("\nDictionary with each item as a pair: ")

print(Dict)
Output:

Empty Dictionary:

{}

Dictionary with the use of Integer Keys:

{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with the use of Mixed Keys:

{1: [1, 2, 3, 4], 'Name': 'Geeks'}

Dictionary with the use of dict():

{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with each item as a pair:

{1: 'Geeks', 2: 'For'}

Result:

Thus program to implement Lists, Tuples and Dictionary in Python is successfully executed.
Viva Questions

Q1.What is the difference between list and tuples?(CO2)

LIST TUPLES

Lists are mutable i.e they can be edited. Tuples are immutable (tuples are lists which can’t be
edited).

Lists are slower than tuples. Tuples are faster than list.

Syntax: list_1 = [10, ‘Chelsea’, 20] Syntax: tup_1 = (10, ‘Chelsea’ , 20)

Q2. What is dictionary?(CO2)

Ans. A dictionary is an associative array of key-value pairs. It’s unordered and requires the
keys to be hashable. Search operations happen to be faster in a dictionary as they use keys for
lookups.
Experiment.No.3
To write a program to find mean, median, mode for the given set of numbers
in a list.(CO1)

.
Program:

from statistics import mean,median,mode

l = [15, 18, 2, 36, 12, 78, 5, 6, 9,18]

print("Mean",mean(l))

print("Median",median(l))

print("Mode",mode(l))

Output:

Mean 19.9

Median 13.5

Mode 18

Result:

Thus a Python program to find the Mean , Median and Mode was created and
executed successfully.

Viva Questions

Q1.How To Select An Element From A List(CO1)

Ans. You can select a element from the list by using the index operator [ ]

Q2. How can you randomize the items of a list in place in Python?(CO1)
Ans: Consider the example shown below:
1 from random import shuffle

2 x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High']

3 shuffle(x)

4 print(x)

The output of the following code is as below.

['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag']

Experiment.No.4

To write a program to find the first n prime numbers (CO3)

Program :

n=int(input("Enter the limit:"))

for num in range(1,n): #iterate between 1 to n

for i in range(2,num): #iterate factors of the num

if num%i==0:

r=num/i

break

else:
print ("Prime number:",num)

Output:

Enter the limit:25

Prime number: 1

Prime number: 2

Prime number: 3

Prime number: 5

Prime number: 7

Prime number: 11

Prime number: 13

Prime number: 17

Prime number: 19

Prime number: 23

Result:

Thus a Python program to find the first n prime numbers was created and executed
successfully.

Viva questions
Q1. What is the output of the following?(CO3)
x = ['ab', 'cd']
for i in x:
print(x)

Ans. [‘ab’, ‘cd’]

Q2. What is the output of the following? (CO3)


i=1
while True:
if i%3 == 0:
break
print(i)

i+=1
Ans. It will show error

Experiment.No.5

Write a Program for checking whether the given number is an even number
or not (CO3)

Program:

n=int(input("Enter a number>"))

if (n % 2 == 0):

print ("EVEN Number")

else:

print ("ODD Number")

Output:

Enter a number >10

EVEN Number

Result:
Thus the Python program to compute given number is a even number or not

Viva Questions
Q1. What is the output of the expression? (CO3)
round(4.576)
Ans.5
This is a built-in function which rounds a number to give precision in decimal digits. In the
above case, since the number of decimal places has not been specified, the decimal number is
rounded off to a whole number. Hence the output will be 5.
Q2. What is the output of the function shown below? (CO3)
all([2,4,0,6])
Ans. False
Explanation: The function all returns false if any one of the elements of the iterable is zero and
true if all the elements of the iterable are non zero. Hence the output of this function will be
false.

Experiment.No.6

Write a program to find the square root of a number (CO3)

Program:

print("Enter 'x' for exit.")

num = input("Enter a number: ")

if num == 'x':

exit()

else:

number = float(num)
number_sqrt = number ** 0.5

print("Square Root of %0.2f is %0.2f" %(number, number_sqrt))

Output:

Enter the number : 121

Square root of the number is 11

Result:

Thus the Python program to find the square root of a number was created
and executed successfully

Viva Questions
Q1.What is the output of the function shown below? (CO3)
import math
abs(math.sqrt(25))
Ans.5.0
Explanation: The abs() function prints the absolute value of the argument passed. For example:
abs(-5)=5. Hence , in this case we get abs(5.0)=5.0.
Q2. What are the outcomes of the functions shown below? (CO3)
sum(2,4,6)
sum([1,2,3])
Ans. Error, 6
Explanation: The first function will result in an error because the function sum() is used to find the
sum of iterable numbers. Hence the outcomes will be Error and 6 respectively.
Experiment.No.7

To Write a program to find the exponentiation (Power of a number) (CO3)

Program:

n=int(input("Enter a number:"))

e=int(input("Enter a number:"))

r=n

for i in range(1,e):

r=n*r

print (n"^"r)

print ("Exponent",r)

Output:

Enter a number:3

Enter a number:2

3^2

Exponent 9

Result:

Thus a Python program to find the exponentiation (Power of a number) was created

and executed successful

Viva Question

Q1.What is returned by math.ceil(3.4)? (CO3)

Ans.4

Explanation: The ceil function returns the smallest integer that is bigger than or equal to
the number itself.
Q2.What is the output of print(math.copysign(3, -1))? (CO3)

Ans. -3.0

Explanation: The copysign function returns a float whose absolute value is that of the
first argument and the sign is that of the second argument.

Experiment.No.8

To write a program to print Fibonacci Series (CO3)

Program:

num = int(input("Enter number of digits you want in series (minimum 2): "))

first = 0

second = 1

print("\nfibonacci series is:")

print(first, ",", second, end=", ")

for i in range(2, num):

next = first + second

print(next, end=", ")

first = second

second = next
Output:

Enter number of digits you want in series (minimum 2): 8

fibonacci series is:

0 , 1, 1, 2, 3, 5, 8, 13,

Result:

Thus a Python programs to print Fibonacci Series was created and executed
successfully.

Viva Questions
Q1. Which of the following methods can be used to find the nth fibonnaci number?(CO3)
Ans. Dynamic programming
Recursion
Iteration

Q2.Suppose the first fibonnaci number is 0 and the second is 1. What is the sixth
fibonnaci number? (CO3)
Ans. 5

Experiment.No.9

To write a program to show Inheritance (CO4)

Program :

class Person(object):
# Constructor

def __init__(self, name):

self.name = name

# To get name

def getName(self):

return self.name

# To check if this person is employee

def isEmployee(self):

return False

# Inherited or Sub class (Note Person in bracket)

class Employee(Person):

# Here we return true

def isEmployee(self):

return True

# Driver code

#if person is of employee class it will return True

emp = Person("Harshit") # An Object of Person

print(emp.getName(), emp.isEmployee())
emp = Employee("Harsh") # An Object of Employee

print(emp.getName(), emp.isEmployee())

Output:

Harshit False

Harsh True

Result:

Thus a Python programs to show Inheritance was created and executed successfully.

Viva Question
Q1. What does built-in function help do in context of classes?(CO4)

Ans. Determines class description of any built-in type.

Q2. What does built-in function type do in context of classes?(CO4)

Ans. Determines the class name of any value.

Experiment.No.10

To achieve functional Polymorphism (CO4)

Program :

def add(x, y, z = 0):

return x + y+z
# functional call

#for two number

print(add(2, 3))

#for three number

print(add(2, 3, 4))

Output:

Result:

Thus a python program to search an element using Binary search technique was created and
executed successfully.

Viva Question
Q1. What is the biggest reason for the use of polymorphism? (CO4)

Ans. The program will have a more elegant design and will be easier to maintain and update.

Q2. A class in which one or more methods are only implemented to raise an exception is
called? (CO4)

Ans. is called an abstract class.


Experiment.No.11

Write a program to print each line of a file in reverse order (CO5)

Program :

input_file=open('D:/a.txt','r')

for line in input_file:

l=len(line) s=' '

while(l>=1):

s=s+line[l-1]

l=l-1

print(s)

input_file.close()

​ # a.txt file contain hello

Output:
olleh

Result:

Thus a python program to print each line of a file in reverse order was created and executed
successfully.
Viva Questions

Q1.What command is used to open a file “c:\temp.txt” in read-mode only?(CO5)

Ans. infile = open(“c:\\temp.txt”, “r”).

Q2. Which commands can be used to read “n” number of characters from a file using the
file object <file>?(CO5)

Ans. file.read(n).

You might also like