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

PYTHON Lab (21CSL46) Manual 4th Sem Final

The document provides information about the Python Programming Laboratory course for the 4th semester Computer Science students. It includes 10 experiments covering Python fundamentals, functions, strings, lists, tuples, dictionaries, files, classes, inheritance and polymorphism. For each experiment, it lists the objectives and provides sample problems along with video links for reference. It aims to help students learn Python concepts through hands-on practice in the laboratory.

Uploaded by

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

PYTHON Lab (21CSL46) Manual 4th Sem Final

The document provides information about the Python Programming Laboratory course for the 4th semester Computer Science students. It includes 10 experiments covering Python fundamentals, functions, strings, lists, tuples, dictionaries, files, classes, inheritance and polymorphism. For each experiment, it lists the objectives and provides sample problems along with video links for reference. It aims to help students learn Python concepts through hands-on practice in the laboratory.

Uploaded by

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

BANGALORE INSTITUTE OF TECHNOLOGY

K.R.ROAD, V.V.PURAM, BANGALORE-560 004

Department of Computer Science & Engineering


PYTHON PROGRAMMING LABORATORY
MANUAL

IV- Sem CSE

21CSL46

Prepared By:
Prof. Prathima M G & Prof. Suma L
PYTHON PROGRAMMING LABORATORY

Course Code 21CSL46 CIE Marks 50


Teaching Hours/Weeks (L: T: P: S) 0: 0: 2: 0 SEE Marks 50
Total Hours of Pedagogy 24 Total Marks 100
Credits 01 Exam Hours 03

Course Objectives:

CLO 1: Demonstrate the use of IDLE or PyCharm IDE to create Python Applications.

CLO 2: Using Python programming language to develop programs for solving real-world
problems.

CLO 3: Implement the Object-Oriented Programming concepts in Python.

CLO 4: Appraise the need for working with various documents like Excel, PDF, Word and Others.

CLO 5: Demonstrate regular expression using python programming

Note: two hours tutorial is suggested for each laboratory sessions.

Prerequisite
 Students should be familiarized about Python installation and setting Python environment
 Usage of IDLE or IDE like PyCharm should be introduced
Python Installation: https://www.youtube.com/watch?v=Kn1HF3oD19c PyCharm
Installation: https://www.youtube.com/watch?v=SZUNUB6nz3g

Sl. No. PART A – List of problems for which student should develop program and execute in
the Laboratory

1 Aim: Introduce the Python fundamentals, data types, operators, flow control and
exception handling in Python

a) Write a python program to find the best of two test average marks out of three
test’s marks accepted from the user.
b) Develop a Python program to check whether a given number is palindrome or not
and also count the number of occurrences of each digit in the input number.

Datatypes: https://www.youtube.com/watch?v=gCCVsvgR2KU
Operators: https://www.youtube.com/watch?v=v5MR5JnKcZI
Flow Control: https://www.youtube.com/watch?v=PqFKRqpHrjw
For loop: https://www.youtube.com/watch?v=0ZvaDa8eT5s
While loop: https://www.youtube.com/watch?v=HZARImviDxg
Exceptions: https://www.youtube.com/watch?v=6SPDvPK38tw
Aim: Demonstrating creation of functions, passing parameters and return values
2
a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program which accepts
a value for N (where N >0) as input and pass this value to the function. Display
suitable error message if the condition for input value is not followed.
b) Develop a python program to convert binary to decimal, octal to hexadecimal using
functions.

Functions: https://www.youtube.com/watch?v=BVfCWuca9nw
Arguments: https://www.youtube.com/watch?v=ijXMGpoMkhQ
Return value: https://www.youtube.com/watch?v=nuNXiEDnM44
3 Aim: Demonstration of manipulation of strings using string methods

a) Write a Python program that accepts a sentence and find the number of words, digits,
uppercase letters and lowercase letters.
b) Write a Python program to find the string similarity between two given strings
Sample Output: Sample Output:
Original string: Original string:
Python Exercises Python Exercises
Python Exercises Python Exercise
Similarity between two said strings: Similarity between two said strings: 1.0
0.967741935483871
Strings: https://www.youtube.com/watch?v=lSItwlnF0eU
String functions: https://www.youtube.com/watch?v=9a3CxJyTq00
4 Aim: Discuss different collections like list, tuple and dictionary

a) Write a python program to implement insertion sort and merge sort using lists
b) Write a program to convert roman numbers in to integer values using dictionaries.

Lists: https://www.youtube.com/watch?v=Eaz5e6M8tL4
List methods: https://www.youtube.com/watch?v=8-RDVWGktuI
Tuples: https://www.youtube.com/watch?v=bdS4dHIJGBc
Tuple operations: https://www.youtube.com/watch?v=TItKabcTTQ4
Dictionary: https://www.youtube.com/watch?v=4Q0pW8XBOkc
Dictionary methods:
https://www.youtube.com/watch?v=oLeNHuORpNY
Aim: Demonstration of pattern recognition with and without using regular expressions
5
a) Write a function called isphonenumber () to recognize a pattern 415-555-4242
without using regular expression and also write the code to recognize the same pattern
using regular expression.
b) Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses ([email protected])

Regular expressions: https://www.youtube.com/watch?v=LnzFnZfHLS4

6 Aim: Demonstration of reading, writing and organizing files.

a) Write a python program to accept a file name from the user and perform
the following operations
1. Display the first N line of the file
2. Find the frequency of occurrence of the word accepted from the user in
the file
b) Write a python program to create a ZIP file of a particular folder which
contains several files inside it.

Files: https://www.youtube.com/watch?v=vuyb7CxZgbU
https://www.youtube.com/watch?v=FqcjKewJTQ0

File organization: https://www.youtube.com/watch?v=MRuq3SRXses


7 Aim: Demonstration of the concepts of classes, methods, objects and inheritance

a) By using the concept of inheritance write a python program to find the area of triangle,
circle and rectangle.
b) Write a python program by creating a class called Employee to store the details of
Name, Employee_ID, Department and Salary, and implement a method to update
salary of employees belonging to a given department.

OOP’s concepts:
https://www.youtube.com/watch?v=qiSCMNBIP2g Inheritance:
https://www.youtube.com/watch?v=Cn7AkDb4pIU
Aim: Demonstration of classes and methods with polymorphism and overriding
8
a) Write a python program to find the whether the given input is palindrome or not (for
both string and integer) using the concept of polymorphism and inheritance.

Overriding: https://www.youtube.com/watch?v=CcTzTuIsoFk
Aim: Demonstration of working with excel spreadsheets and web scraping

a) Write a python program to download the all XKCD comics


9
b) Demonstrate python program to read the data from the spreadsheet and write the data
in to the spreadsheet

Web scraping: https://www.youtube.com/watch?v=ng2o98k983k

Excel: https://www.youtube.com/watch?v=nsKNPHJ9iPc
10 Aim: Demonstration of working with PDF, word and JSON files

a) Write a python program to combine select pages from many PDFs


b) Write a python program to fetch current weather data from the JSON file

c) PDFs: https://www.youtube.com/watch?v=q70xzDG6nls
https://www.youtube.com/watch?v=JhQVD7Y1bsA
d) https://www.youtube.com/watch?v=FcrW-ESdY-A
e) Word files: https://www.youtube.com/watch?v=ZU3cSl51jWE JSON files:
https://www.youtube.com/watch?v=9N6a-VLBa2I
Python (Full Course): https://www.youtube.com/watch?v=_uQrJ0TkZlc
Pedagogy For the above experiments the following pedagogy can be considered. Problem based
learning, Active learning, MOOC, Chalk &Talk

PART B – Practical Based Learning

A problem statement for each batch is to be generated in consultation with the co-examiner and student
should develop an algorithm, program and execute the program for the given problem with appropriate
outputs.

Course Outcomes:
CO 1: Demonstrate proficiency in handling of loops and creation of functions.
CO 2: Identify the methods to create and manipulate lists, tuples and dictionaries.

CO 3: Discover the commonly used operations involving regular expressions and file system.

CO 4: Interpret the concepts of Object-Oriented Programming as used in Python.

CO 5: Determine the need for scraping websites and working with PDF, JSON and other file formats.
PROGRAM -1

1a) Write a Python program to find the best of two test average marks out of three test marks
accepted by the user.

m1 = int(input("Enter marks for test1 : "))

m2 = int(input("Enter marks for test2 : "))

m3 = int(input("Enter marks for test3 : "))

if m1 <= m2 and m1 <= m3:

avgMarks = (m2+m3)/2

elif m2 <= m1 and m2 <= m3:

avgMarks = (m1+m3)/2

elif m3 <= m1 and m2 <= m2:

avgMarks = (m1+m2)/2

print("Average of best two test marks out of three test’s marks is", avgMarks);

OUTPUT

Enter marks for test1: 45

Enter marks for test2: 39

Enter marks for test3: 48

Average of best two test marks out of three test’s marks is 46.5
1b) Develop a Python program to check whether a given number is palindrome or not and also
count the number of occurrences of each digit in the input number.

val = int(input("Enter a value : "))

str_val = str(val)

if str_val == str_val[::-1]:

print("Palindrome")

else:

print("Not Palindrome")

for i in range(10):

if str_val.count(str(i)) > 0:

print(str(i),"appears", str_val.count(str(i)), "times");

OUTPUT:

Enter a value: 1234234

Not Palindrome

1 appears 1 times

2 appears 2 times

3 appears 2 times

4 appears 2 times

Enter a value: 12321

Palindrome

1 appears 2 times

2 appears 2 times

3 appears 1 times
PROGRAM -2

2a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program that accepts a value
for N (where N >0) as input and pass this value to the function. Display a suitable error message
if the condition for input value is not followed.

def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fn(n-1) + fn(n-2)

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

if num > 0:
print("fn(", num, ") = ",fn(num) , sep ="")
else:
print("Error in input")

OUTPUT:

Enter a number : 5

fn(5) = 3

Enter a number : -5

Error in input
2b) Develop a python program to convert binary to decimal, octal to hexadecimal using
functions.

def btod(a,length):
sum=0
for i in range(0,length):
index=int(a.pop())#extracting LSD of binary number
value=index*pow(2,i)
sum=sum+value
return int(sum)

def input_binary():
n=input('enter the binary number\n')

length=len(n)
a=[]
for i in range(0,length):
char=(n[i])#extracting each digit of binary number from first to last
if(char=='0' or char=='1'):
a.append(char)#inserting the digits of binary number into list from first to last*/
else:
print('invalid binary number')
exit(0)
decimal=btod(a,length)
print('the decimal equavalent of binary number '+n+' is',decimal)

def input_octal():
print("Enter the Octal Number: ")
octnum = int(input())

chk = 0
i=0
decnum = 0
while octnum != 0:
rem = octnum % 10
if rem > 7: # checking for the valid octal number
chk = 1
break
decnum = decnum + (rem * (8 ** i)) #converting octal to decimal
i=i+1
octnum = int(octnum / 10)

if chk == 0:
i=0
hexdecnum = []
while decnum != 0:
rem = decnum % 16
if rem < 10:
rem = rem + 48 # to get the ASCII equivalent of a digit
else:
rem = rem + 55 #to get the ASCII equivalent of an alphabet
rem = chr(rem)
hexdecnum.insert(i, rem)
i=i+1
decnum = int(decnum / 16)

print("\nEquivalent Hexadecimal Value is: ")


i= i-1
while i >= 0:
print(end=hexdecnum[i])
i=i-1
print()

else:
print("\nInvalid Input!")

char='Y'
while(char=='Y'):
print('enter the choice 1. binary to decimal','\t','2. octal to hexadecimal','\n')
choice=int(input())
if choice==1:
input_binary()
elif choice==2:
input_octal()
else:
print('enter your choice correctly')
exit(0)
print('Do you want to continue? Press Y else N')
char=input()
if char=='N':
exit(1)

OUTPUT:
enter the choice 1. binary to decimal 2. octal to hexadecimal

1
enter the binary number

10010
the decimal equivalent of binary number 10010 is 18
Do you want to continue? Press Y else N

enter the choice 1. binary to decimal 2. octal to hexadecimal


2

Enter the Octal Number:


345

Equivalent Hexadecimal Value is:


E5

Do you want to continue? Press Y else N


Y

enter the choice 1. binary to decimal 2. octal to hexadecimal


2

Enter the Octal Number:

786

Invalid Input!
Do you want to continue? Press Y else N
Y

enter the choice 1. binary to decimal 2. octal to hexadecimal

enter the binary number


1002

invalid binary number


2b. Alternate / Shortened Program

def bin_to_dec():
bin=int(input("Enter a binary number : "))
dec=0
i=0
while bin!=0:
dec+=(bin%10)*(2**i)
i+=1
bin//=10
print("Decimal Equivalent is : ",dec)

def oct_to_hex():
oct=int(input("Enter an octal number : "))
dec=0
i=0
while oct!=0:
dec+=(oct%10)*(8**i)
i+=1
oct//=10
hex =""
while dec!=0:
rem=dec%16
if rem<10:
hex+=str(rem)
else:
hex+= chr(ord('A')+rem-10)
dec//=16
hex=hex[::-1]
print("Hexadecimal Equivalent is : ", hex)

print("BINARY TO DECIMAL CONVERSION")


bin_to_dec()
print("\n\nOCTAL TO HEXADECIMAL CONVERSION")
oct_to_hex()
PROGRAM -3

3a) Write a Python program that accepts a sentence and find the number of words, digits,
uppercase letters, and lowercase letters.

sentence = input("Enter a sentence: ")


words = digits = upper = lower = 0

# Splitting the sentence using split() method , by default split is by spaces


# Return value - list of strings

split_sentence = sentence.split()
print("The result of split() on input sentence is : \n"+str(split_sentence)+"\n")

words = len(split_sentence )

for c in sentence:
if c.isdigit():
digits = digits + 1
elif c.isupper():
upper = upper + 1
elif c.islower():
lower = lower + 1

print ("No of Words: ", words)


print ("No of Digits: ", digits)
print ("No of Uppercase letters: ", upper)
print ("No of Lowercase letters: ", lower)

OUTPUT:

Enter a sentence: Rama went to Devaraja market to pick 2 kgs of vegetable

The result of split() on input sentence is :

['Rama', 'went', 'to', 'Devaraja', 'market', 'to', 'pick', '2', 'kgs', 'of', 'vegetable']

No of Words: 11

No of Digits: 1

No of Uppercase letters: 2

No of Lowercase letters: 42
3b) Write a Python program to find the string similarity between two given strings.

str1 = input("Enter String 1 \n")


str2 = input("Enter String 2 \n")

if len(str2) < len(str1):


short = len(str2)
long = len(str1)
else:
short = len(str1)
long = len(str2)
matchCnt = 0
for i in range(short):
if str1[i] == str2[i]:
matchCnt += 1
print("Similarity between two said strings:")
print(matchCnt/long)

OUTPUT:

Enter String 1
Python Exercises
Enter String 2
Python Exercises
Similarity between two said strings:
1.0
Enter String 1
Python Exercises
Enter String 2
Python Exercise
Similarity between two said strings: 0.9375
PROGRAM -4

4a) Write a python program to implement insertion sort and merge sort using lists.

import random
def merge_sort(rec):
if len(rec) > 1:
mid = len(rec) // 2
left_half = rec[:mid]
right_half = rec[mid:]

merge_sort(left_half)
merge_sort(right_half)
i=j=k=0

while i < len(left_half) and j < len(right_half):


if left_half[i] < right_half[j]:
rec[k] = left_half[i]
i += 1
else:
rec[k] = right_half[j]
j += 1
k += 1

while i < len(left_half):


rec[k] = left_half[i]
i += 1
k += 1
while j < len(right_half):
rec[k] = right_half[j]
j += 1
k += 1
return rec

def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j= i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key

n=int(input('enter the number of elements: ' ))


my_list = []
for i in range(n):
my_list.append(random.randint(0, 999))

print("\nUnsorted List")
print(my_list)
print("Sorting using Insertion Sort")
insertion_sort(my_list)
print(my_list)

my_list = []
for i in range(n):
my_list.append(random.randint(0, 999))
print("\nUnsorted List")
print(my_list)
print("Sorting using Merge Sort")
merge_sort(my_list)
print(my_list)

OUTPUT:

enter the number of elements :10

Unsorted List

[79, 910, 988, 291, 117, 139, 914, 295, 935, 485]

Sorting using Insertion Sort

[79, 117, 139, 291, 295, 485, 910, 914, 935, 988]

Unsorted List

[927, 778, 404, 369, 176, 836, 85, 675, 40, 987]

Sorting using Merge Sort

[40, 85, 176, 369, 404, 675, 778, 836, 927, 987]
4b) Write a program to convert Roman numbers into integer values using dictionaries.

def roman_to_int(s):
rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
int_val = 0
for i in range(len(s)):
if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]:
int_val += rom_val[s[i]] - 2 * rom_val[s[i - 1]]
else:
int_val += rom_val[s[i]]
return str(int_val)

print("Roman numerals to integers using Dictionaries")


s=input('enter the roman number: ')
res=roman_to_int(s)
print('The interger value is:'+res)

OUTPUT:
Roman numerals to integers using Dictionaries

enter the roman number: MCMIV

The interger value is:1904

enter the roman number : MMMCMLXXXVI

The interger value is:3986


PROGRAM -5

5a) Write a function called isphonenumber( ) to recognize a pattern 415-555-4242 without using
regular expression and also write the code to recognize the same pattern using regular
expression.

import re

#Without using Regular Expression:

def isphonenumber(number):
if len(number) != 12:
return False
if number[3] != '-' or number[7] != '-':
return False
for i in range(12):
if i == 3 or i == 7:
continue
if not number[i].isdigit():
return False
return True

#using RegExpr

def isphonenumber_reg(number):
pattern = r"\d{3}-\d{3}-\d{4}"
match = re.fullmatch(pattern, number)
return match is not None

#main function
ph_num=str(input('enter the phone number in ddd-ddd-dddd format to validate'))
print('enter your choice')
print('Press 1.without RegExpression \t 2. using RegExpression')
choice=int(input())
if choice==1:
res=isphonenumber(ph_num)
if res==True:
print('The phone No.'+str(ph_num)+' is valid')
else:
print('The Phone No.' + str(ph_num) + ' is invalid')
elif choice==2:
res = isphonenumber_reg(ph_num)
if res == True:
print('The phone No.' + str(ph_num) + ' is valid')
else:
print('The Phone No.' + str(ph_num) + ' is invalid')
else:
print('enter the correct option')
exit(0)

OUTPUT:

enter the phone number in ddd-ddd-dddd format to validate: 187-000-2094

enter your choice

Press 1.without RegExpression 2. using RegExpression

The phone No.187-000-2094 is valid

enter the phone number in ddd-ddd-dddd format to validate: 111-000-3904

enter your choice

Press 1.without RegExpression 2. using RegExpression

The phone No.111-000-3904 is valid


5b) Develop a Python program that could search the text in a file for phone numbers
(+919900889977) and email addresses ([email protected])

import re

# Define the regular expression for phone numbers

phone_regex = re.compile(r'\+\d{12}')

email_regex = re.compile(r'[A-Za-z0-9._]+@[A-Za-z0-9]+\.[A-Z|a-z]{2,}')

# Open the file for reading

with open('example.txt', 'r') as f:

# Loop through each line in the file

for line in f:

# Search for phone numbers in the line

matches = phone_regex.findall(line)

# Print any matches found

for match in matches:

print(match)

matches = email_regex.findall(line)

# Print any matches found

for match in matches:

print(match)

OUTPUT:
+918151894220
+829392938876
+919900889977

[email protected]
PROGRAM -6

6a) Write a python program to accept a file name from the user and perform the following
operations.

1. Display the first N line of the file

2. Find the frequency of occurrence of the word accepted by the user in the file

import os.path
import sys

fname = input("Enter the filename : ")


if not os.path.isfile(fname):
print("File", fname, "doesn't exists")
sys.exit(0)
infile = open(fname, "r")
n=int(input('enter the number of lines to be read : '))

lineList = infile.readlines()
for i in range(n):
print(i+1, ":", lineList[i])

word = input("Enter a word : ")


cnt = 0
for line in lineList:
cnt += line.count(word)

print("The word","\"", word,"\"", "appears", cnt, "times in the file")

OUTPUT:

Enter the filename : story.txt

enter the number of lines to be read : 2

1 : Artificial intelligence (AI) is intelligence demonstrated by machines,

2 : as opposed to intelligence displayed by humans or by other animals.

Enter a word : intelligence

The word " intelligence " appears 4 times in the file


6b) Write a Python program to create a ZIP file of a particular folder that contains several files
inside it.

import os
import sys
import pathlib
import zipfile
dirName = input("Enter Directory name that you want to backup : ")
if not os.path.isdir(dirName):
print("Directory", dirName, "doesn't exists")
sys.exit(0)
curDirectory = pathlib.Path(dirName)
number = 1
while True:
zipFilename = os.path.basename(curDirectory) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number = number + 1
print(f'Creating {zipFilename}...')
with zipfile.ZipFile(zipFilename, mode="w") as archive:
for file_path in curDirectory.rglob("*"):
archive.write(file_path, arcname=file_path.relative_to(curDirectory))
if os.path.isfile(zipFilename):
print("Archive", zipFilename, "created successfully")
else:
print("Error in creating zip archive")

OUTPUT:
Enter Directory name that you want to backup : sample_folder_testing
Creating sample_folder_testing_4.zip...
Archive sample_folder_testing_4.zip created successfully
PROGRAM -7

7a) By using the concept of inheritance write a python program to find the area of a triangle,
circle, and rectangle.

import math
class Shape:
def area(self):
pass

class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height

class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2

class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width

while(True):
print('1. Area of Triangle 2. Area of Circle 3. Area of Rectangle',"\n")
choice=int(input('enter your choice'))
if choice==1:
b=int(input('enter base\n'))
h = int(input('enter height\n'))
triangle = Triangle(b, h)
print("Area of triangle:", triangle.area())
elif choice==2:
r=float(input('enter the radius\n'))
circle = Circle(r)
print("Area of circle:", circle.area())
elif choice==3:
b=int(input('enter base\n'))
l = int(input('enter length\n'))
rectangle = Rectangle(b, l)
print("Area of rectangle:", rectangle.area())
else:
print('invalid choice')
exit(0)

OUTPUT:
1. Area of Triangle 2. Area of Circle 3. Area of Rectangle

enter your choice1

enter base

enter height

Area of triangle: 3.0

1. Area of Triangle 2. Area of Circle 3. Area of Rectangle

enter your choice2

enter the radius


2.4

Area of circle: 18.09557368467721

1. Area of Triangle 2. Area of Circle 3. Area of Rectangle

enter your choice3

enter base

enter length

Area of rectangle: 35

1. Area of Triangle 2. Area of Circle 3. Area of Rectangle

enter your choice4

invalid choice
7b) Write a Python program by creating a class called Employee to store the details of Name,
Employee_ID, Department, and Salary, and implement a method to update the salary of
employees belonging to a given department.

class Employee:
def __init__(self, name, employee_id, department, salary):
self.name = name
self.employee_id = employee_id
self.department = department
self.salary = salary

def update_salary_by_department(self, department, percent_increase):


if self.department == department:
self.salary *= (1 + percent_increase / 100)

no_of_employees=int(input('enter the number of employee detatils required'))


employees=[]
# Print updated salaries
#for employee in employees:
# print(employee.name, employee.salary)
for i in range(no_of_employees):
print("enter",i,'th','employee details')
print("employee name")
name=input()
print("employee id")
id=input()
print("employee dept")
dept=input()
print("employee salary")
sal=int(input())
employees.append(Employee(name,id,dept,sal))
print('EmpName\t EmpId\t EmpDept\t EmpSalary\n')
for emp in employees:
print(emp.name,'\t',emp.employee_id,'\t',emp.department,'\t',emp.salary,'\n')
dept=input('enter the department to update the salary')
# Increase salaries of Sales department employees by 10%
for employee in employees:
if employee.department==dept:
employee.update_salary_by_department(dept, 10)

for employee in employees:


print(employee.name, employee.salary)

OUTPUT:
enter the number of employee detatils required2
enter 0 th employee details
employee name
rahul
employee id
1
employee dept
cs
employee salary
10000
enter 1 th employee details
employee name
saketh
employee id
2
employee dept
is
employee salary
20000

EmpName EmpId EmpDept EmpSalary

rahul 1 cs 10000

saketh 2 is 20000

enter the department to update the salary cs


rahul 11000.0
saketh 20000
PROGRAM -8

8. Write a Python program to find whether the given input is palindrome or not (for both string
and integer) using the concept of polymorphism and inheritance.

class PaliStr:
def __init__(self):
self.isPali = False

def chkPalindrome(self, myStr):


print('parent')
if myStr == myStr[::-1]:
self.isPali = True
else:
self.isPali = False

return self.isPali

class PaliInt(PaliStr):
def __init__(self):
self.isPali = False

def chkPalindrome(self, val):


print('child')
temp = val
rev = 0
while temp != 0:
dig = temp % 10
rev = (rev*10) + dig
temp = temp //10

if val == rev:
self.isPali = True
else:
self.isPali = False

return self.isPali

st = input("Enter a string : ")

stObj = PaliStr()
if stObj.chkPalindrome(st):
print("Given string is a Palindrome")
else:
print("Given string is not a Palindrome")

val = int(input("Enter a integer : "))

intObj = PaliInt()
if intObj.chkPalindrome(val):
print("Given integer is a Palindrome")
else:
print("Given integer is not a Palindrome")

OUTPUT:
Enter a string : sas

parent

Given string is a Palindrome

Enter a integer : 1221

child

Given integer is a Palindrome


PROGRAM -9

9a) Write a Python program to download all XKCD comics.

#! python3
# downloadXkcd.py - Downloads every single XKCD comic.
import requests, os, bs4
url = 'http://xkcd.com' # starting url
os.makedirs('xkcd2', exist_ok=True) # store comics in ./xkcd
while not url.endswith('#'):
# Download the page.
print('Downloading page %s...' % url)
res = requests.get(url)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text,'html.parser')
# Find the URL of the comic image.
comicElem = soup.select('#comic img')
if comicElem == []:
print('Could not find comic image.')
else:
comicUrl = 'http:' + comicElem[0].get('src')
# Download the image.
print('Downloading image %s...' % (comicUrl))
res = requests.get(comicUrl)
res.raise_for_status()
# Save the image to ./xkcd.
imageFile = open(os.path.join('xkcd2', os.path.basename(comicUrl)), 'wb')
for chunk in res.iter_content(100000):
imageFile.write(chunk)
imageFile.close()
# Get the Prev button's url.
prevLink = soup.select('a[rel="prev"]')[0]
url = 'http://xkcd.com' + prevLink.get('href')
print('Done.')

OUTPUT:

Downloading https://imgs.xkcd.com/comics/barrel_cropped_(1).jpg...

Downloading https://imgs.xkcd.com/comics/radians_are_cursed.png...

Downloading https://imgs.xkcd.com/comics/presents_for_biologists.png...
9b) Demonstrate a python program to read the data from the spreadsheet and write the data into
the spreadsheet.
OUTPUT:
Enter state code for finding capital KA
Corresponding capital for code KA is Bengaluru
Enter state code for finding language TS
Corresponding language for code TS is Telugu
PROGRAM -10

10a) Write a Python program to combine select pages from many PDFs.

from PyPDF2 import PdfWriter, PdfReader

num = int(input("Enter page number you want combine from multiple documents "))

pdf1 = open('DAA MODULE 4.pdf', 'rb')


pdf2 = open('DAA MODULE 5.pdf', 'rb')

pdf_writer = PdfWriter()

pdf1_reader = PdfReader(pdf1)
page = pdf1_reader.pages[num - 1]
pdf_writer.add_page(page)

pdf2_reader = PdfReader(pdf2)
page = pdf2_reader.pages[num - 1]
pdf_writer.add_page(page)

with open('output.pdf', 'wb') as output:


pdf_writer.write(output)

OUTPUT:

Enter page number you want combine from multiple documents - 3

Initially take any two pdf files and chose first three pages to combine and give the result in an output
file.
10b) Write a Python program to fetch current weather data from the JSON file.

# Python code to display schematic weather details


import requests
#Sending requests to get the IP Location Information
res = requests.get('https://ipinfo.io/')
# Receiving the response in JSON format
data = res.json()
# Extracting the Location of the City from the response
citydata = data['city']
# Prints the Current Location
print(citydata)
# Passing the City name to the url
url = 'https://wttr.in/{}'.format(citydata)
# Getting the Weather Data of the City
res = requests.get(url)
# Printing the results!
print(res.text)

OUTPUT:
VIVA QUESTIONS
What is Python?
1. Python is one of the most widely-used and popular programming languages, was developed by
Guido van Rossum and released first on February 20, 1991.
2. Python is a free and open-source language with a very simple and clean syntax which makes it easy
for developers to learn Python.
3. It supports object-oriented programming and is most commonly used to perform general-purpose
programming.
4. Python is used in several domains like Data Science, Machine Learning, Deep Learning, Artificial
Intelligence, Scientific Computing Scripting, Networking, Game Development Web Development,
Web Scraping, and various other domains, System Scripting, Software Development, Complex
Mathematics.
What are the benefits of using Python language as a tool in the present scenario?
The following are the benefits of using Python language:
Object-Oriented Language, High-Level Language, Dynamically Typed language, Extensive support
Libraries, Presence of third-party modules, Open source and community development, Portable and
Interactive, Portable across Operating systems.
Is Python a compiled language or an interpreted language?
Python is a partially compiled language and partially interpreted language. ‘#’ is used to comment on
everything that comes after on the line.
Difference between a Mutable datatype and an Immutable data type?
Mutable data types can be edited i.e., they can change at runtime. Eg – List, Dictionary, etc.
Immutable data types can not be edited i.e., they can not change at runtime. Eg – String, Tuple, etc.
What is a lambda function?
A lambda function is an anonymous function. This function can have any number of parameters but,
can have just one statement.
Pass means performing no operation or in other words, it is a placeholder in the compound statement,
where there should be a blank left and nothing has to be written there.

Python provides various web frameworks to develop web applications.


The popular python web frameworks are Django, Pyramid, Flask.
 Python's standard library supports for E-mail processing, FTP, IMAP, and other Internet protocols.
 Python's SciPy and NumPyhelp in scientific and computational application development.
 Python's Tkinter library supports to create desktop-based GUI applications.
What is the difference between / and // in Python?
// represents floor division whereas / represents precise division. 5//2 = 2 5/2 = 2.5
Yes, indentation is required in Python. A Python interpreter can be informed that a group of
statements belongs to a specific block of code by using Python indentation. Indentations make the code
easy to read for developers in all programming languages but in Python, it is very important to indent
the code in a specific order.

What is Scope in Python?


The location where we can find a variable and also access it if required is called the scope of a variable.
Python Local variable: Local variables are those that are initialized within a function and are unique
to that function. It cannot be accessed outside of the function.
Python Global variables: Global variables are the ones that are defined and declared outside any
function and are not specified to any function.
Module-level scope: It refers to the global objects of the current module accessible in the program.
Outermost scope: It refers to any built-in names that the program can call. The name referenced is
located last among the objects in this scope.

Python documentation strings(or docstrings) provide a convenient way of associating


documentation with Python modules, functions, classes, and methods.
Declaring Docstrings: The docstrings are declared using ”’triple single quotes”’ or “””triple double
quotes””” just below the class, method, or function declaration. All functions should have a docstring.
Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or
using the help function.

What is slicing in Python?


Python Slicing is a string operation for extracting a part of the string, or some part of a list. With this
operator, one can specify where to start the slicing, where to end, and specify the step. List slicing
returns a new list from the existing list.

PIP is an acronym for Python Installer Package which provides a seamless interface to install
various Python modules. It is a command-line tool that can search for packages over the internet and
install them without any user interaction.
Sample Programs

1. Python program to print "Hello Python"


print ('Hello Python')

2. Python program to do arithmetical operations


# Store input numbers:

num1 = input('Enter first number: ')

num2 = input('Enter second number: ')

# Add two numbers

sum = float(num1) + float(num2)

# Subtract two numbers

min = float(num1) - float(num2)

# Multiply two numbers

mul = float(num1) * float(num2)

#Divide two numbers

div = float(num1) / float(num2)

# Display the sum

print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

# Display the subtraction

print('The subtraction of {0} and {1} is {2}'.format(num1, num2, min))

# Display the multiplication

print('The multiplication of {0} and {1} is {2}'.format(num1, num2, mul))

# Display the division

print('The division of {0} and {1} is {2}'.format(num1, num2, div))


3. Python program to find the area of a triangle

a=5

b=6

c=7

# Uncomment below to take inputs from the user

# a = float(input('Enter first side: '))

# b = float(input('Enter second side: '))

# c = float(input('Enter third side: '))

# calculate the semi-perimeter

s = (a + b + c) / 2

# calculate the area

area = (s*(s-a)*(s-b)*(s-c)) ** 0.5

print('The area of the triangle is %0.2f' %area)

4. Python program to swap two variables

#swapping of 2 numbers

p=int(input("enter the value of a"))

q=int(input("enter the value of b"))

print('Before Swapping the value of p=',p,'and q=',q)

temp=p

p=q

q=temp

print('After swapping the value of p=',p,'and q=',q)


5. Python program to find the sum and average of natural numbers up to n where n is provided
by user.

n=int(input("Enter upto which number you want sum and average"))

sum=0

for i in range(0,n+1):

sum=sum+i

avg=sum/n

print("Result of sum is",sum)

print("Result of Average",avg)

6. WAP to find Factorial of a number using for loop

fact=1

n=int(input("enter the value of n to find factorial of a given number"))

for i in range(1,n+1) :

fact=fact*i

print(fact)

7. WAP to find Factorial of a number using while loop

fact=1

i=1

n=int(input("enter the value of n to find factorial of a given number"))

while i<=n :

fact=fact*i

i=i+1

print(fact)
8. WAP to find fibonacci series using Iterative:

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

n1, n2 = 0, 1

count = 0

if n <= 0:

print("Please enter a positive integer")

elif n == 1:

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

print(n1)

else:

print("Fibonacci sequence:")

while count < n:

print(n1)

next = n1 + n2

n1 = n2

n2 = next

count += 1

9.WAP to find fibonacci series using recursion:

def fib(n):

if n <= 1:

return n

else:

return(fib(n-1) + fib(n-2))
nterms = int(input("How many terms? "))

if nterms<= 0:

print("Plese enter a positive integer")

else:

print("Fibonacci sequence:")

for i in range(nterms):

print(fib(i))

10 . WAP to find largest among three numbers, input by user

n1=int(input("enter first number"))

n2=int(input("enter sec number"))

n3=int(input("enter third number"))

if n1>n2 and n1>n3 :

print("n1 is larger")

elif n2>n3 and n2>n1 :

print("n2 is larger")

else :

print("n3 is larger")

11. WAP to print first ten programs using for loop .

for i in range(1,11) :

print(i)
12. WAP to print first ten programs using while loop.

I=1

while i<=10:

print(i)

i=i+1

13. WAP to check whether a person is eligible for voting.

age=input()

type(age)

x=int(age)

if x>18 :

print("eligible")

else :

print("not ")

14. WAP to print grades obtained by the students and print the appropriate message.

marks=input()

type(marks)

x=int(marks)

if x>=90 and x<100:

print('distinction')

elif x>=80 and x<=90:

print("first")

else :

print("fail")
15.WAP to find factorial of given number using for loop.

fact=1

for i in range(1,6) :

fact*=i

print(fact)

16.WAP to find factorial of given number using while loop.

fact=1

i=1

n=int(input())

while i<=n:

fact=fact*i

i=i+1

print(fact)

17. WAP to find factorial of given number using functions.

def fact(n) :

fact=1

i=1

while i<=n :

fact*=i

i=i+1

return fact

#print(fact)
n=int(input("enter the number to find factoral of a given number"))

print(fact(n))

18.WAP to find gcd of 2 numbers.

def gcd(a,b):

if b==0:

return a

else :

return gcd(b,a%b)

n1=int(input("enter the first number"))

n2=int(input("enter the second number"))

print(gcd(n1,n2))

19. Python program to generate a random number

20. Python program to convert kilometers to miles.

21. Python program to convert Celsius to Fahrenheit

22. Python program to display calendar

23. Python Program to Check if a Number is Positive, Negative or Zero

24. Python Program to Check if a Number is Odd or Even

25. Python Program to Check Leap Year

26. Python Program to Check Prime Number

27. Python Program to Print all Prime Numbers in an Interval

28. Python Program to Find the Factorial of a Number

29. Python Program to Display the multiplication Table

30. Python Program to Print the Fibonacci sequence


31.Python Program to Check Armstrong Number

32.Python Program to Find Armstrong Number in an Interval

Python Additional Programs

1. Python program to print "Hello Python"


2. Python program to do arithmetical operations
3. Python program to find the area of a triangle
4. Python program to solve quadratic equation
5. Python program to swap two variables
6. Python program to generate a random number
7. Python program to convert kilometers to miles
8. Python program to convert Celsius to Fahrenheit
9. Python program to display calendar
10. Python Program to Check if a Number is Positive, Negative or Zero
11. Python Program to Check if a Number is Odd or Even
12. Python Program to Check Leap Year
13. Python Program to Check Prime Number
14. Python Program to Print all Prime Numbers in an Interval
15. Python Program to Find the Factorial of a Number
16. Python Program to Display the multiplication Table
17. Python Program to Print the Fibonacci sequence
18. Python Program to Check Armstrong Number
19. Python Program to Find Armstrong Number in an Interval
20. Python Program to Find the Sum of Natural Numbers
21. Python Function Programs
22. Python Program to Find LCM
23. Python Program to Find HCF
24. Python Program to Convert Decimal to Binary, Octal and Hexadecimal
25. Python Program To Find ASCII value of a character
26. Python Program to Make a Simple Calculator
27. Python Program to Display Calendar
28. Python Program to Display Fibonacci Sequence Using Recursion
29. Python Program to Find Factorial of Number Using Recursion
30. Python Number Programs
31. Python program to check if the given number is a Disarium Number
32. Python program to print all disarium numbers between 1 to 100
33. Python program to check if the given number is Happy Number
34. Python program to print all happy numbers between 1 and 100
35. Python program to determine whether the given number is a Harshad Number
36. Python program to print all pronic numbers between 1 and 100
37. Python Array Programs
38. Python program to copy all elements of one array into another array
39. Python program to find the frequency of each element in the array
40. Python program to left rotate the elements of an array
41. Python program to print the duplicate elements of an array
42. Python program to print the elements of an array
43. Python program to print the elements of an array in reverse order
44. Python program to print the elements of an array present on even position
45. Python program to print the elements of an array present on odd position
46. Python program to print the largest element in an array
47. Python program to print the smallest element in an array
48. Python program to print the number of elements present in an array
49. Python program to print the sum of all elements in an array
50. Python program to right rotate the elements of an array
51. Python program to sort the elements of an array in ascending order
52. Python program to sort the elements of an array in descending order
53. Python Matrix Programs
54. Python Program to Add Two Matrices
55. Python Program to Multiply Two Matrices
56. Python Program to Transpose a Matrix
57. Python String Programs
58. Python Program to Sort Words in Alphabetic Order
59. Python Program to Remove Punctuation From a String
60. Python Program to reverse a string
61. Python Program to convert list to string
62. Python Program to convert int to string
63. Python Program to concatenate two strings
64. Python Program to generate a Random String
65. Python Program to convert Bytes to string
66. Python List Programs
67. Python Program to append element in the list
68. Python Program to compare two lists
69. Python Program to convert list to dictionary
70. Python Program to remove an element from a list
71. Python Program to add two lists
72. Python Program to convert List to Set
73. Python Program to convert list to string
74. Python Dictionary Programs
75. Python Program to create a dictionary
76. Python Program to convert list to dictionary
77. Python Program to sort a dictionary
78. Python Program to Merge two Dictionaries
79. Python Searching and Sorting Programs
80. Binary Search in Python
81. Linear Search in Python
82. Bubble Sort in Python
83. Insertion Sort in Python
84. Heap Sort in Python
85. Merge Sort in Python
86. Python Circular Linked List Programs
87. Python program to create a Circular Linked List of N nodes and count the number of nodes
88. Python program to create a Circular Linked List of n nodes and display it in reverse order
89. Python program to create and display a Circular Linked List
90. Python program to delete a node from the beginning of the Circular Linked
List
91. Python program to delete a node from the end of the Circular Linked List
92. Python program to delete a node from the middle of the Circular Linked List
93. Python program to find the maximum and minimum value node from a circular linked list
94. Python program to insert a new node at the beginning of the Circular Linked
List
95. Python program to insert a new node at the end of the Circular Linked List
96. Python program to insert a new node at the middle of the Circular Linked
List
97. Python program to remove duplicate elements from a Circular Linked List
98. Python program to search an element in a Circular Linked List
99. Python program to sort the elements of the Circular Linked List
100. Python Doubly Linked List Programs
101. Python program to convert a given binary tree to doubly linked list
102. Python program to create a doubly linked list from a ternary tree
103. Python program to create a doubly linked list of n nodes and count the number of nodes
104. Python program to create a doubly linked list of n nodes and display it in reverse order
105. Python program to create and display a doubly linked list
106. Python program to delete a new node from the beginning of the doubly linked list
107. Python program to delete a new node from the end of the doubly linked list
108. Python program to delete a new node from the middle of the doubly linked
list
109. Python program to find the maximum and minimum value node from a
doubly linked list
110. Python program to insert a new node at the beginning of the Doubly Linked
list
111. Python program to insert a new node at the end of the Doubly Linked List
112. Python program to insert a new node at the middle of the Doubly Linked List
113. Python program to remove duplicate elements from a Doubly Linked List
114. Python program to rotate doubly linked list by N nodes
115. Python program to search an element in a doubly linked list

You might also like