0% found this document useful (0 votes)
3 views41 pages

Python Lab Manual FINAL

The document is a Python Programming Lab Manual for the IV Semester at Sharnbasva University, detailing course objectives and a list of programming exercises aimed at developing practical skills in Python. It covers various topics including data types, control statements, functions, file handling, and object-oriented programming, along with examples and expected outputs. Additionally, it provides an introduction to Python, its features, installation steps, and a brief history.

Uploaded by

laxmibagodi25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views41 pages

Python Lab Manual FINAL

The document is a Python Programming Lab Manual for the IV Semester at Sharnbasva University, detailing course objectives and a list of programming exercises aimed at developing practical skills in Python. It covers various topics including data types, control statements, functions, file handling, and object-oriented programming, along with examples and expected outputs. Additionally, it provides an introduction to Python, its features, installation steps, and a brief history.

Uploaded by

laxmibagodi25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Department of computer science and

Engineering

Python Programming Lab Manual


(22CSL48)
IV SEMESTER
Academic Year – 2022-23

Faculty of Engineering & Technology (Exclusively for Women),


Sharnbasva University, Kalaburagi
PYTHON PROGRAMMING LAB

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

Using Regular expressions, develop a Python program to

a. Identify a word with a sequence of one upper case letter


followed by lower case letters.
5. b. Find all the patterns of “1(0+)1” in a given string.

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)

a. Develop a program to print the 10 most frequently File Handling


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
dictionary slice of first 10 items]
b. Develop a program to sort the contents of a text file and
8. write the sorted contents into a separate text file. [Hint:
String method strip(), list method sort(), append(), and file
method open(), readlines(), and write()].
c. 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.
PYTHON PROGRAMMING LAB

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.

 Python is Interpreted − Python is processed at runtime by the interpreter. You


do not need to compile your program before executing it. This is similar to PERL
and PHP.
 Python is Interactive − You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
 Python is Object-Oriented − Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
 Python is a Beginner's Language − Python is a great language for the beginner-
level programmers and supports the development of a wide range of
applications from simple text processing to WWW browsers to games.

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

Python's features include −

 Easy-to-learn − Python has few keywords, simple structure, and a clearly


defined syntax. This allows the student to pick up the language quickly.
PYTHON PROGRAMMING LAB

 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 −

 It supports functional and structured programming methods as well as OOP.


 It can be used as a scripting language or can be compiled to byte-code for
building large applications.
 It provides very high-level dynamic data types and supports dynamic type
checking.
 It supports automatic garbage collection.
 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

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

Steps to be followed and remembered:

Step 1: Select Version of Python to Install.


Step 2: Download Python Executable Installer.
Step 3: Run Executable Installer.
Step 4: Verify Python Was Installed on Windows
Step 5: Verify Pip Was Installed. Step
6: Add Python Path to Environment Variables (Optional)
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.’ ‘ ‘

name=str(input("enter the name of the student: "))

usn=str(input("enter the usn of the student: "))

m1=int(input("enter the marks of subject 1: "))

m2=int(input("enter the marks of subject 2: "))

m3=int(input("enter the marks of subject 3: "))

#m4=int(input("enter the marks of subject 4:"))

#m5=int(input("enter the marks of subject 5:"))

total=m1+m2+m3

per=total/3

print("total:",total)

print("percentage:",per)

if(per>=60):

print("first division")

elif(per>=50 and per<=59):

print("second division:")

elif(per>=40 and per<=49):

print("third division:")

else:

print("fail...")
PYTHON PROGRAMMING LAB

OUTPUT

== case – 1==

enter the name of the student: AMBIKA

enter the usn of the student: SW20AIM001

enter the marks of subject 1: 88

enter the marks of subject 2: 99

enter the marks of subject 3: 78

total: 265

percentage: 88.33333333333333

first division

==case -2==

enter the name of the student: GANGA

enter the usn of the student: SW20AIM007

enter the marks of subject 1: 55

enter the marks of subject 2: 45

enter the marks of subject 3: 45

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

name=str(input("enter the name of the person:"))

birth_year=int(input("Enter Year of Birth:"))

current_year=int(input("Enter Current Year :"))

age=current_year-birth_year

if (age>60):

print("Senior")

else:

print("Not Senior")

OUTPUT

enter the name of the person:AMBIKA

Enter Year of Birth:2003

Enter Current Year :2023

Not Senior

enter the name of the person:GANGA

Enter Year of Birth:1947

Enter Current Year :2023

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()

number = int(input( "Enter the number of elements you want: "))

print ('Enter numbers in array: ')

for i in range(int(number)):

n = input( "number : ")

a.append ( int ( n ))

print("Given 'n' numbers: ")

print(a)

m = statistics.mean ( a )

v = statistics.variance ( a )

st = statistics.stdev ( a )

print( "Mean: ",m)

print( "Variance: ",v)

print( "Standard Deviation: ",st)

OUTPUT

Enter the number of elements you want: 3

Enter numbers in array:

number : 3

number : 4

number : 5

Given 'n' numbers:

[3, 4, 5]

Mean: 4

Variance: 1

Standard Deviation: 1.0


PYTHON PROGRAMMING LAB

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

print("a is type of",type(a))

print("b is type of",type(b))

print("c is type of",type(c))

num1=int(input("enter first number:"))

num2=int(input("enter second number:"))

print("addition of num1 and num2:",num1+num2)

print("subtraction of num1 and num2:",num1-num2)

print("multiplication of num1 and num2:",num1*num2)

print("division of num1 and num2:",num1/num2)

print("remainder of num1 and num2:",num1%num2)

print("exponent of num1 and num2:",num1**num2)

print("floored division of num1 and num2:",num1//num2)

OUTPUT

a is type of <class 'int'>

b is type of <class 'float'>

c is type of <class 'complex'>

enter first number:6

enter second number:7

addition of num1 and num2: 13

subtraction of num1 and num2: -1

multiplication of num1 and num2: 42

division of num1 and num2: 0.8571428571428571

remainder of num1 and num2: 6

exponent of num1 and num2: 279936floored division of num1 and num2: 0


PYTHON PROGRAMMING LAB

2b. Write a program to create, concatenate and print a string and accessing sub-string

from a given string.'''

s1=input("Enter first String : ")

s2=input("Enter second String : ")

print("First string is : ",s1)

print("Second string is : ",s2)

print("concatenations of two strings :",s1+s2)

print("Substring of given string :",s1[1:4])

OUTPUT

Enter first String : MADAM

Enter second String : MAM

First string is : MADAM

Second string is : MAM

concatenations of two strings : MADAMMAM

Substring of given string : ADA


PYTHON PROGRAMMING LAB

2c. Write a python script to print the current date in the following format Sun May 29

02:26:23 IST 2017

import time;

ltime=time.localtime();

print(time.strftime("%a %b %d %H:%M:%S %Z %Y",ltime)); #returns the formatted time

'''

%a : Abbreviated weekday name.

%b : Abbreviated month name.

%d : Day of the month as a decimal number [01,31].

%H : Hour (24-hour clock) as a decimal number [00,23].

%M : Minute as a decimal number [00,59].

%S : Second as a decimal number [00,61].

%Z : Time zone name (no characters if no time zone exists).

%Y : Year with century as a decimal number.'''

OUTPUT

====== RESTART: C:/Users/HP/AppData/Local/Programs/Python/Python311/tm.py ======

Tue Mar 28 16:30:08 India Standard Time 2023


PYTHON PROGRAMMING LAB

2d. Read a multi-digit number (as char) from the console.

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

num = input("Enter the multi digit number: ")

print(char_frequency(num))

OUTPUT

Enter the multi digit number: hello

{'h': 1, 'e': 1, 'l': 2, 'o': 1}


PYTHON PROGRAMMING LAB

3a. ''' Write a python program to find largest of three numbers '''

num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: "))

num3 = int(input("Enter third number: "))

if (num1 > num2) and (num1 > num3):

largest = num1

elif (num2 > num1) and (num2 > num3):

largest = num2

else:

largest = num3

print("The largest number is",largest)

OUTPUT

====== RESTART: C:/Users/HP/AppData/Local/Programs/Python/Python311/P3B.PY =====

Enter first number: 8

Enter second number: 9

Enter third number: 7

The largest number is 9


PYTHON PROGRAMMING LAB

3b. Develop a program to generate Fibonacci Sequence of length(N). Read N from the console

nterms = int(input("How many terms? "))

# first two terms

n1, n2 = 0, 1

count = 0

# check if the number of terms is valid

if nterms <= 0:

print("Please enter a positive integer")

# if there is only one term, return n1

elif nterms == 1:

print("Fibonacci sequence upto",nterms,":")

print(n1)

# generate fibonacci sequence

else:

print("Fibonacci sequence:")

while count < nterms:

print(n1)

nth = n1 + n2

# update values

n1 = n2

n2 = nth

count += 1
PYTHON PROGRAMMING LAB

OUTPUT

How many terms? 4

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

print("\n factorial of",num,"=",fact)

except ValueError:

print("\n invalid input!")

def binomialCoeff(n, k):

if k > n:

return 0

if k == 0 or k == n:

return 1

# Recursive Call

return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k)


PYTHON PROGRAMMING LAB

OUTPUT

enter a number:4

factorial of 4 = 1

factorial of 4 = 2

factorial of 4 = 6

factorial of 4 = 24
PYTHON PROGRAMMING LAB

4 a. Implementing program using Functions (Largest number in a list, area of shape)

#Largest number in a list

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":

l=int(input("enter rectangle length:"))

b=int(input("enter rectangle breadth:"))

rect_area=l*b

print(f"the area of rectangle is {rect_area}")

elif name=="square":

s=int(input("enter square side length:"))

sqt_area=s*s

print(f"the area of square is {sqt_area}")

elif name=="triangle":

h=int(input("enter triangle height length:"))

b=int(input("enter triangle breadth length:"))

tri_area=0.5*h*b

print(f"the area of triangle is {tri_area}")

elif name=="circle":

r=int(input("enter circle radius length:"))

pi=3.14

circ_area=pi*r*r
print(f"the area of circle is {circ_area}")

elif name=="parallelogram":

b=int(input("enter parallelogram base length:"))

h=int(input("enter parallelogram height length:"))


PYTHON PROGRAMMING LAB

para_area=b*h

print(f"the area of parallelogram is {para_area}")

else:

print("sorry! this shape is not available.")

if __name ==" main ":

print("calculate shape area")


shape_name=input("enter the name of shape whose area you want to find:")

calculate_area(shape_name)

OUTPUT

calculate shape area

enter the name of shape whose area you want to find:triangle

enter triangle height length:5

enter triangle breadth length:3

the area of triangle is 7.5


PYTHON PROGRAMMING LAB

4b. implementing a real-time/technical application using Exception handling (Divide by Zeroerror,


Voter’s age validity, student mark range validation)

# divide by Zero error

a=int(input("enter a:"))

b=int(input("enter b:"))

try:

c=((a+b)/(a-b))

if a==b:

raise ZeroDivisionError

except ZeroDivisionError:

print("a/b result is 0")

else:

print(c)

#2.Voter's Age Validity

print("Voter's Age Validity")

def voting():

try:

age=int(input("Enter your age"))

if age>18:

print("Eligible to vote")

else:

print("Not eligible to vote")

except:

print("age must be a valid number")

voting()

# student mark range validation

name=input("enter the student name:")

regno=input("enter the student register number:")

try:

mark1=int(input("enter the mark1:"))


PYTHON PROGRAMMING LAB

mark2=int(input("enter the mark2:"))

if(0<=mark1<=100)and(0<=mark2<=100):

print("marks are in the range")

else:

raise ValueError("marks are not in range")

except ValueError as err:

print(err)

finally:

print("thankyou,you have successfully checked")

OUTPUT

enter a:5

enter b:5

a/b result is 0

Voter's Age Validity

Enter your age32

Eligible to vote

enter the student name:jerry


enter the student register number:sw21aim001

enter the mark1:70

enter the mark2:30

marks are in the range

thankyou,you have successfully checked


PYTHON PROGRAMMING LAB
5.Using Regular expressions, develop a Python program to

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

5.b. Find all the patterns of “1(0+)1” in a given string.

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)):

# We found 0 and last character was '1',


# state change
if (str[i] == '0' and last == '1'):
while (str[i] == '0'):
i += 1
# After the stream of 0's, we got a '1',
# counter incremented
if (str[i] == '1'):
counter += 1

# Last character stored


last = str[i]
i += 1
return counter
ans = patternCount(str)
print (ans)
OUTPUT:
Found 2
PYTHON PROGRAMMING LAB
6a. SET1 and SET2 are two sets that contain unique integers. SET3 is to be created by taking the
union or intersection of SET1 and SET2 using the user defined function Operation (). Perform
either union or intersection by reading the choice from the user. Do not use built-in function union()
and intersection () and also the operators “|” and “&”.

set1=[1,2,3,4,5,6]

set2=[1,2,3,5,7,9,10]

set3=[]

def operation(choice):

if choice=="union":

for row in set2:

set1.append(row)

for col in set1:

set3.append(col)

elif choice=="intersection":

for row in set1:

if row in set2:

set3.append(row)

for col in set2:

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'}

print("\n dictionary is:",dict1)

print("\n student name is:",dict1['stuname'])

print("\n student city is:",dict1['stucity'])

print("\n all key in dictionary")

for x in dict1:

print(x)

print("\n all key in dictionary")

for x in dict1:

print(dict1[x])

dict1["phno"]=6884762859

print("updated dictionary is:",dict1)

dict1["stuname"]="jerry"

print("updated dictionary is:",dict1)

dict1.pop("stuage")

print("updated dictionary is:",dict1)

print("length of dictionary is:",len(dict1))

dict2=dict1.copy()

print("\n new dictionary is:",dict2)

dict1.clear()

print("updated dictionary is:",dict1)


PYTHON PROGRAMMING LAB

OUTPUT

dictionary is: {'stdno': '532', 'stuname': 'naveen', 'stuage': '21', 'stucity': 'hyderabad'}

student name is: naveen

student city is: hyderabad

all key in dictionary

stdno

stuname

stuage

stucity

all key in dictionary

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}

length of dictionary is: 4

new dictionary is: {'stdno': '532', 'stuname': 'jerry', 'stucity': 'hyderabad', 'phno': 6884762859}

updated dictionary is: {}


PYTHON PROGRAMMING LAB

7. Implementing program using Strings. (Reverse, palindrome, character count, replacing


characters)

''' REVERSE A STRING '''

def reversed_string(text):

if len(text) == 1:

return text

return reversed_string(text[1:]) + text[:1]

print(reversed_string("Python Programming!"))

''' PALINDROME '''

def isPalindrome(s):

return s == s[::-1]

s = input("enter any string :")

ans = isPalindrome(s)

if ans:

print(s,"Yes it's a palindrome")

else:

print(s,"No it's not a palindrome")

'''CHARACTER COUNT'''

def count_chars(txt):

result = 0

for char in txt:

result += 1 # same as result = result + 1

return result

text=input("enter any string")

print("no.of characters in a string",count_chars(text))

'''REPLACING CHARACTERS'''

string = "python programming language is powerful"

print(string.replace("p", "P",1))

print(string.replace("p", "P"))

OUTPUT
PYTHON PROGRAMMING LAB

!gnimmargorP nohtyP

enter any string :MADAM

MADAM Yes it's a palindrome

enter any string :MAA

MAA No it's not a palindrome

enter any string MANGO

no.of characters in a string 6

Python programming language is powerful

Python Programming language is Powerful


PYTHON PROGRAMMING LAB

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]

from collections import Counter

import re

text = """The Python Software Foundation (PSF) is a 501(c)(3) non-profit

corporation that holds the intellectual property rights behind

the Python programming language. We manage the open source licensing

for Python version 2.1 and later and own and protect the trademarks

associated with Python. We also run the North American PyCon conference

annually, support other Python conferences around the world, and

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")

input file: sample.txt

ZEBRA AND OX ARE GOOD FRIENDS. DOGS ARE VERY LOYAL AND FAITHFUL.

Output file: output.txt

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):

# Backup the entire contents of "folder" into a zip file.

folder = os.path.abspath(folder) # make sure folder is absolute

# Figure out the filename this code should used based on what files already exist.

number = 1

while True:

zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'

if not os.path.exists(zipFilename):

break

number = number + 1

# Create the zip file.

print('Creating %s...' % (zipFilename))

backupZip = zipfile.ZipFile(zipFilename, 'w')

# Walk the entire folder tree and compress the files in each folder.

for foldername, subfolders, filenames in os.walk(folder):

print('Adding files in %s...' % (foldername))

# Add the current folder to the ZIP file.

backupZip.write(foldername)

# Add all the files in this folder to the ZIP file.

for filename in filenames:

if filename.startswith(os.path.basename(folder) + '_') and filename.endswith('.zip'):

continue # don't backup the backup ZIP files

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 = []

def __init (self,name,rn):

self.name = name

self.rn = rn

def getMarks(self, m1, m2, m3):

Student.marks.append(m1)

Student.marks.append(m2)

Student.marks.append(m3)

def displayData(self):

print (&quot;Name is: &quot;, self.name)

print (&quot;USN is: &quot;, self.rn)

print (&quot;Marks in subject 1: &quot;, Student.marks[0])

print (&quot;Marks in subject 2: &quot;, Student.marks[1])

print (&quot;Marks in subject 3: &quot;, Student.marks[2])

print (&quot;Marks are: &quot;, Student.marks)

print (&quot;Total Marks are: &quot;, self.total())

print (&quot;Average Marks are: &quot;, self.average())

def total(self):

return (Student.marks[0] + Student.marks[1] +Student.marks[2])

def average(self):

return ((Student.marks[0] + Student.marks[1] +Student.marks[2])/3)


PYTHON PROGRAMMING LAB

name = input(&quot;Enter the name: &quot;)

r = input(&quot;Enter the USN: &quot;)

m1 = int (input(&quot;Enter the marks in the first subject: &quot;))

m2 = int (input(&quot;Enter the marks in the second subject: &quot;))

m3 = int (input(&quot;Enter the marks in the third subject: &quot;))

s1 = Student(name,r)

s1.getMarks(m1, m2, m3)

s1.displayData()

OUTPUT

Enter the name: AKSHARA

Enter the USN: SW22AIM001

Enter the marks in the first subject: 99

Enter the marks in the second subject: 89

Enter the marks in the third subject: 88

Name is: AKSHARA

USN is: SW22AIM001

Marks in subject 1: 99

Marks in subject 2: 89

Marks in subject 3: 88

Marks are: [99, 89, 88]

Total Marks are: 276

Average Marks are: 92.0


PYTHON PROGRAMMING LAB

#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

#10. c. Implementing program using modules and python Standard


Library(Matplotlib)
import matplotlib.pyplot as plt
days = [1,2,3,4,5]
sleeping =[7,8,6,11,7]
eating = [2,3,4,3,2]
working =[7,8,7,2,2]
playing = [8,5,7,8,13]
slices = [7,2,2,13]
activities = ['sleeping','eating','working','playing']
cols = ['c','m','r','b']
plt.pie(slices,labels=activities, colors=cols,
startangle=90,
shadow= True,
explode=(0,0.1,0,0),
autopct='%1.1f%%')
plt.title('Pie Plot')
plt.show()

Output
PYTHON PROGRAMMING LAB

#10. d. Implementing program using modules and python Standard


Library(Scipy)
import matplotlib.pyplot as plt
from scipy import interpolate
import numpy as np
x = np.arange(5, 20)
y = np.exp(x/3.0)
f = interpolate.interp1d(x, y)
x1 = np.arange(6, 12)
y1 = f(x1) # use interpolation function returned by `interp1d`
plt.plot(x, y, 'o', x1, y1, '--')
plt.show()

Output

You might also like