Python Lab Manual FINAL
Python Lab Manual FINAL
Engineering
List of Programs
Course Learning objectives: This course will enable students to:
• Develop program to solve real world problems using python programming.
• Develop the programs using the concepts of control statements, data structures & files.
• Apply features of object-oriented and Numpy, pandas package to develop
computationallyintensive programming & interpret the data.
Part-
A
No. Title of the experiment Expected Skill /Ability
a. Develop a program to read the student’s details like Name, Basics of Python
USN, and Marks in three subjects. Display the student’s
details, total marks, and percentage with suitable
messages.
1. b. Develop a program to read the name and year of birth of a
person. Display whether the person is a senior citizen or
not.
c. Read N numbers from the console and create a list.
Develop a
program to print mean, variance, and standard deviation
with suitable messages.
a. Write a program to demonstrate different numbered data Basics of Python
types in
Python and perform a different arithmetic operation on
numbers in Python.
b. Write a program to create, concatenate and print a string
2. andaccess a sub-string from a given string.
c. Write a Python script to print the current date in the
followingformat “Sun May 29 02:26:23 IST 2017”.
d. Read a multi-digit number (as char) from the console.
Developa program to print the frequency of each digit
with suitable
messages.
a. Develop a program to find the largest of three numbers Conditional Statements
b. Develop a program to generate a Fibonacci sequence of
length(N). Read N from the console.
3. c. Write a program to calculate the factorial of a number.
Developa program to compute the binomial coefficient
(Given N and
R).
a. Implementing programs using Functions (Largest number Functions and
in a list, area of shape)
4. b. implementing a real-time/technical application using Exception Handling
Exception handling (Divide by Zero error, Voter’s age
validity,student mark range validation)
PYTHON PROGRAMMING LAB
a. SET1 and SET2 are two sets that contain unique integers. Create and Perform
SET3 is to be created by taking the union or intersection
of SET1 and SET2 using the user-defined function Union and
Operation (). Perform either union or intersection by intersection
reading the choice from the user. Do not use built-in
function union () and intersection () and also the operators operations on sets
6. “|” and “&”.
b. The Dictionary “DICT1” contains N Elements and each
element in the dictionary has the operator as the KEY and
operands as VALUES. Perform the operations on Create a Dictionary and
operands using operators stored as keys. Display the
operates using user-
results of all operations.
defineded function
Implementing programs using Strings. (Reverse, String operations
7. palindrome,character count, replacing characters)
Develop a program that uses class Students which prompts Classes and Objects
the User to enter marks in three subjects and calculate total
usability
marks, Percentage and display the scorecard details. [Hint:
9. Use a list to store the marks in three subjects and total
marks. Use_init(
) method to initialize name, USN and the lists to store
marksand total, Use getMarks() method to read marks into
the list, and display() method to display the scorecard
details.]
Implementing program using modules and python pandas,
StandardLibraries (pandas, Numpy, Matplotlib, Scipy) Numpy
10.
,Matplotlib, Scipy
Usability
PYTHON PROGRAMMING LAB
1. Introduction to Python
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.
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the
National Research Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
SmallTalk, and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU General
Public License (GPL).
Python is now maintained by a core development team at the institute, although Guido van
Rossum still holds a vital role in directing its progress.
Python Features
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs
than shell scripting.
Apart from the above-mentioned features, Python has a big list of good features, few are
listed below −
2. Installation
There are many interpreters available freely to run Python scripts like IDLE
(Integrated Development Environment) which is installed when you install the python
software from http://python.org/downloads/.
PYTHON PROGRAMMING LAB
‘ ‘ ‘1 a. Develop a program to read the students details like Name, USN, and Marks in three subjects.
Display the student’s details, total marks and percentage with suitable messages.’ ‘ ‘
total=m1+m2+m3
per=total/3
print("total:",total)
print("percentage:",per)
if(per>=60):
print("first division")
print("second division:")
print("third division:")
else:
print("fail...")
PYTHON PROGRAMMING LAB
OUTPUT
== case – 1==
total: 265
percentage: 88.33333333333333
first division
==case -2==
total: 145
percentage: 48.333333333333336
third division:
PYTHON PROGRAMMING LAB
1b. Develop a program to read the name and year of birth of a person. Display whether the person
is a senior citizen or not
age=current_year-birth_year
if (age>60):
print("Senior")
else:
print("Not Senior")
OUTPUT
Not Senior
Senior
PYTHON PROGRAMMING LAB
1c. Read N numbers from the console and create a list. To find mean, variance and standard
deviation of given numbers
import statistics
a = list()
for i in range(int(number)):
a.append ( int ( n ))
print(a)
m = statistics.mean ( a )
v = statistics.variance ( a )
st = statistics.stdev ( a )
OUTPUT
number : 3
number : 4
number : 5
[3, 4, 5]
Mean: 4
Variance: 1
2a. Write a program to demonstrate different number data types in python and perform different
Arithmetic operations on numbers in python.
a=10
b=8.5
c=2.05j
OUTPUT
2b. Write a program to create, concatenate and print a string and accessing sub-string
OUTPUT
2c. Write a python script to print the current date in the following format Sun May 29
import time;
ltime=time.localtime();
'''
OUTPUT
Develop a program to print the frequency of each digit suitable for messages.
def char_frequency(str1):
dict = {}
for n in str1:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
return dict
print(char_frequency(num))
OUTPUT
3a. ''' Write a python program to find largest of three numbers '''
largest = num1
largest = num2
else:
largest = num3
OUTPUT
3b. Develop a program to generate Fibonacci Sequence of length(N). Read N from the console
n1, n2 = 0, 1
count = 0
if nterms <= 0:
elif nterms == 1:
print(n1)
else:
print("Fibonacci sequence:")
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
PYTHON PROGRAMMING LAB
OUTPUT
Fibonacci sequence:
2
PYTHON PROGRAMMING LAB
3c. Write a function to calculate the factorial of a number. Develop a program to compute the
binomial coefficient (Given N and R)
print("enter a number:",end='')
try:
num=int(input())
fact=1
for i in range(1,num+1):
fact=fact*i
except ValueError:
if k > n:
return 0
if k == 0 or k == n:
return 1
# Recursive Call
OUTPUT
enter a number:4
factorial of 4 = 1
factorial of 4 = 2
factorial of 4 = 6
factorial of 4 = 24
PYTHON PROGRAMMING LAB
def mymax(list1):
max=list1[0]
for x in list1:
if x>max:
max=x
return max
list1=[10,20,30,40,55,99]
print("largest element is:",mymax(list1))
#Area of shape
def calculate_area(name):
if name=="rectangle":
rect_area=l*b
elif name=="square":
sqt_area=s*s
elif name=="triangle":
tri_area=0.5*h*b
elif name=="circle":
pi=3.14
circ_area=pi*r*r
print(f"the area of circle is {circ_area}")
elif name=="parallelogram":
para_area=b*h
else:
calculate_area(shape_name)
OUTPUT
a=int(input("enter a:"))
b=int(input("enter b:"))
try:
c=((a+b)/(a-b))
if a==b:
raise ZeroDivisionError
except ZeroDivisionError:
else:
print(c)
def voting():
try:
if age>18:
print("Eligible to vote")
else:
except:
voting()
try:
if(0<=mark1<=100)and(0<=mark2<=100):
else:
print(err)
finally:
OUTPUT
enter a:5
enter b:5
a/b result is 0
Eligible to vote
a. Identify a word with a sequence of one upper case letter followed by lower case letters.
import re
def search(ip_str):
re_exp = '[A-Z]+[a-z]+$'
if re.search(re_exp, ip_str):
print('Yes, the required sequence exists!')
else:
print('No, the required sequence does not exists!')
ip_str = input("Enter the string: ")
search(ip_str)
output:
Enter the string: AbvfjNDb
Yes, the required sequence exists!
Enter the string: abbb
No, the required sequence does not exists!
PYTHON PROGRAMMING LAB
import re
str = '11001001'
match = re.search('1(0+)1', str)
# If-statement after search() tests if it succeeded
if match:
print('found') ## 'found word:cat'
else:
print('did not find')
def patternCount(str):
# Variable to store the last character
last = str[0]
i = 1; counter = 0
while (i < len(str)):
set1=[1,2,3,4,5,6]
set2=[1,2,3,5,7,9,10]
set3=[]
def operation(choice):
if choice=="union":
set1.append(row)
set3.append(col)
elif choice=="intersection":
if row in set2:
set3.append(row)
if col in set1:
set3.append(col)
return set(set3)
print(operation("intersection"))
OUTPUT
#intersection
{1, 2, 3, 5}
#union
{1, 2, 3, 4, 5, 6, 7, 9, 10}
PYTHON PROGRAMMING LAB
6b. The Dictionary “DICT1” contains N Elements and each element in the dictionary has the
operator as the KEY and operands as VALUES. Perform the operations on operands using
operators stored as keys. Display the results of all operations.
dict1={'stdno':'532','stuname':'naveen','stuage':'21','stucity':'hyderabad'}
for x in dict1:
print(x)
for x in dict1:
print(dict1[x])
dict1["phno"]=6884762859
dict1["stuname"]="jerry"
dict1.pop("stuage")
dict2=dict1.copy()
dict1.clear()
OUTPUT
dictionary is: {'stdno': '532', 'stuname': 'naveen', 'stuage': '21', 'stucity': 'hyderabad'}
stdno
stuname
stuage
stucity
532
naveen
21
hyderabad
updated dictionary is: {'stdno': '532', 'stuname': 'naveen', 'stuage': '21', 'stucity': 'hyderabad', 'phno':
6884762859}
updated dictionary is: {'stdno': '532', 'stuname': 'jerry', 'stuage': '21', 'stucity': 'hyderabad', 'phno':
6884762859}
updated dictionary is: {'stdno': '532', 'stuname': 'jerry', 'stucity': 'hyderabad', 'phno': 6884762859}
new dictionary is: {'stdno': '532', 'stuname': 'jerry', 'stucity': 'hyderabad', 'phno': 6884762859}
def reversed_string(text):
if len(text) == 1:
return text
print(reversed_string("Python Programming!"))
def isPalindrome(s):
return s == s[::-1]
ans = isPalindrome(s)
if ans:
else:
'''CHARACTER COUNT'''
def count_chars(txt):
result = 0
return result
'''REPLACING CHARACTERS'''
print(string.replace("p", "P",1))
print(string.replace("p", "P"))
OUTPUT
PYTHON PROGRAMMING LAB
!gnimmargorP nohtyP
8. a. Develop a program to print the 10 most frequently appearing words in a text file.
[Hint: Use a dictionary with distinct words and their frequency of occurrences. Sort the
dictionary in the reverse order of frequency and display the dictionary slice of the first
10 items]
import re
for Python version 2.1 and later and own and protect the trademarks
associated with Python. We also run the North American PyCon conference
fund Python related development with our grants program and by funding
special projects."""
words = re.findall('\w+',text)
print(Counter(words).most_common(10))
Output:
[('Python', 6), ('the', 6), ('and', 5), ('We', 2), ('with', 2), ('The', 1), ('Software', 1), ('Foundation', 1),
('PSF', 1), ('is', 1)]
PYTHON PROGRAMMING LAB
8b. Develop a program to sort the contents of a text file and write the sorted contents
into a separate text file.
def sorting(filename):
infile = open(filename)
words = []
for line in infile:
temp = line.split()
for i in temp:
words.append(i)
infile.close()
words.sort()
outfile = open("result.txt", "w")
for i in words:
outfile.writelines(i)
outfile.writelines(" ")
outfile.close()
sorting("sample.txt")
ZEBRA AND OX ARE GOOD FRIENDS. DOGS ARE VERY LOYAL AND FAITHFUL.
AND AND ARE ARE DOGS FAITHFUL. FRIENDS. GOOD LOYAL OX VERY ZEBRA
PYTHON PROGRAMMING LAB
8c. Develop a program to backing up a given Folder (Folder in a current working directory)
into a ZIP File by using relevant modules and suitable methods.
import zipfile, os
def backupToZip(folder):
# Figure out the filename this code should used based on what files already exist.
number = 1
while True:
if not os.path.exists(zipFilename):
break
number = number + 1
# Walk the entire folder tree and compress the files in each folder.
backupZip.write(foldername)
backupZip.write(os.path.join(foldername, filename))
backupZip.clos-e()
print('Done.')
backupToZip('C:\\delicious')
PYTHON PROGRAMMING LAB
Output:
Creating delicious_1.zip...
Do
PYTHON PROGRAMMING LAB
9. Develop a program that uses class Students which prompts the User to enter marks in three subjects
and calculate total marks,Percentage and display the score card details. [Hint: Use list to store the marks in
three subjects and total marks. Use_init() method to initialize name, USN and the lists to store marks
and total, Use getMarks() method to read marks into the list, and display() method to display the
score card details.]
class Student:
marks = []
self.name = name
self.rn = rn
Student.marks.append(m1)
Student.marks.append(m2)
Student.marks.append(m3)
def displayData(self):
def total(self):
def average(self):
s1 = Student(name,r)
s1.displayData()
OUTPUT
Marks in subject 1: 99
Marks in subject 2: 89
Marks in subject 3: 88
#10. '''Implementing program using modules and python Standard Library (pandas)'''
import pandas as pd
df = pd.DataFrame(
{
"Name": [ "Braund, Mr. Owen Harris",
"Allen, Mr. William Henry",
"Bonnell, Miss. Elizabeth",],
"Age": [22, 35, 58], "Sex": ["male", "male", "female"],
}
)
print(df)
print(df["Age"])
ages = pd.Series([22, 35, 58], name= "age")
print(ages)
df["Age"].max()
print(ages.max())
print(df.describe())
Output
Name Age Sex
0 Braund, Mr. Owen Harris 22 male
1 Allen, Mr. William Henry 35 male
2 Bonnell, Miss. Elizabeth 58 female
0 22
1 35
2 58
Name: Age, dtype: int64
0 22
1 35
2 58
Name: age, dtype: int64
58
Age
count 3.000000
mean 38.333333
std 18.230012
min 22.000000
25% 28.500000
PYTHON PROGRAMMING LAB
#10.b. Implementing program using modules and python Standard Library (Numpy)
import numpy as np
a = np.arange(6)
a2 = a[np.newaxis, :]
a2.shape
#Array Creation and functions:
a = np.array([1, 2, 3, 4, 5, 6])
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(a[0])
print(a[1])
np.zeros(2)
np.ones(2)
np.arange(4)
np.arange(2, 9, 2)
np.linspace(0, 10, num=5)
x = np.ones(2, dtype=np.int64)
print(x)
arr = np.array([2, 1, 5, 3, 7, 4, 6, 8])
np.sort(arr)
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
np.concatenate((a, b))
#Array Dimensions:
array_example = np.array([[[0, 1, 2, 3], [4, 5, 6, 7]], [[0, 1, 2, 3], [4, 5, 6, 7]],
[[0 ,1 ,2, 3], [4, 5, 6, 7]]])
array_example.ndim
array_example.size
array_example.shape
a = np.arange(6)
print(a)
b=a.reshape(3, 2)
print(b)
np.reshape(a, newshape=(1, 6), order='C')
Output
[1 2 3 4]
[5 6 7 8]
[1 1]
[0 1 2 3 4 5]
[[0 1]
[2 3]
[4 5]]
PYTHON PROGRAMMING LAB
Output
PYTHON PROGRAMMING LAB
Output