Python Lab Manual 1
Python Lab Manual 1
LAB MANUAL
CLASS/SECTION- CSE
LAB MANUAL
SEMESTER-V
BRANCH - CSE
CONTENTS
To be the fountainhead of novel ideas & innovations in science & technology &
persist to be a foundation of pride for all Indians.
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)
INTRODUCTION TO PYTHON
Introduction
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
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.
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.
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):
• Change to the directory and tell the computer to compile and install the program
cd Python-3.4/
$ ./configure --prefix=$HOME/python3_install
$ make
$ 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
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.
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.
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 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
(Intel)] on win32
>>>
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'>
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")
print("Done")
if 1:
print("True")
print("Done")
>>> 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
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,
Program:
#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)
10.5 150.0
Constants:
A constant is a type of variable whose value cannot be changed. It is helpful to think of constants
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:
● Integers.
● Floating-Point Numbers.
● Complex Numbers.
● Built-In Functions. Math. Type Conversion. Iterables and Iterators. Composite Data Type.
Input output :
We use the print() function to output data to the standard output device (screen)
Program:
a=5
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
Program:
Enter a number: 10
>>> num
'10'
Viva Questions
Q1.What is Python?(CO1)
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?
● 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 :
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])
# my_list[4.0]
# Nested List
# Nested indexing
# Output: a
print(n_list[0][1])
# Output: 5
print(n_list[1][3])
Output:
# empty tuple
# Output: ()
my_tuple = ()
print(my_tuple)
# Output: (1, 2, 3)
my_tuple = (1, 2, 3)
print(my_tuple)
# nested tuple
print(my_tuple)
print(my_tuple)
# Output:
#3
# 4.6
# dog
a, b, c = my_tuple
print(a)
print(b)
print(c)
Output:
()
(1, 2, 3)
4.6
dog
Dict = {}
print(Dict)
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
Output:
Empty Dictionary:
{}
Result:
Thus program to implement Lists, Tuples and Dictionary in Python is successfully executed.
Viva Questions
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)
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:
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
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
3 shuffle(x)
4 print(x)
Experiment.No.4
Program :
if num%i==0:
r=num/i
break
else:
print ("Prime number:",num)
Output:
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)
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):
else:
Output:
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
Program:
if num == 'x':
exit()
else:
number = float(num)
number_sqrt = number ** 0.5
Output:
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
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
Viva Question
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
Program:
num = int(input("Enter number of digits you want in series (minimum 2): "))
first = 0
second = 1
first = second
second = next
Output:
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
Program :
class Person(object):
# Constructor
self.name = name
# To get name
def getName(self):
return self.name
def isEmployee(self):
return False
class Employee(Person):
def isEmployee(self):
return True
# Driver code
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)
Experiment.No.10
Program :
return x + y+z
# functional call
print(add(2, 3))
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)
Program :
input_file=open('D:/a.txt','r')
while(l>=1):
s=s+line[l-1]
l=l-1
print(s)
input_file.close()
Output:
olleh
Result:
Thus a python program to print each line of a file in reverse order was created and executed
successfully.
Viva Questions
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).