0% found this document useful (0 votes)
17 views30 pages

Python Programming Lab Manual for BE

manual

Uploaded by

poojarisujan27
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)
17 views30 pages

Python Programming Lab Manual for BE

manual

Uploaded by

poojarisujan27
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

MITE - 16

MANGALORE INSTITUTE OF TECHNOLOGY & ENGINEERING


Accredited by NAAC with A+ Grade, An ISO 9001: 2015 Certified Institution
(A Unit of Rajalaxmi Education Trust®, Mangalore - 575001)
Affiliated to V.T.U., Belagavi, Approved by AICTE, New Delhi

Laboratory Manual
DEPARTMENT OF COMPUTER SCIENCE &
ENGINEERING
(Accredited by NBA)

FOURTH SEMESTER B.E.

Course Title: PYTHON PROGRAMMING LABORATORY

Course Code: 21CSL46


Department of Computer Science & Engineering

2021 Scheme
DEPARTMENT OF COMPUTER SCIENCE &
ENGINEERING
(Accredited by NBA)

Course Title/Code: PYTHON PROGRAMMING LABORATORY


[21CSL46]

VISION OF THE INSTITUTE


"To attain perfection in providing Globally Competitive Quality Education to all our students and
also benefit the global community by using our strength in Research and Development"

MISSION OF THE INSTITUTE


"To establish world class educational institutions in their respective domains, which shall be centers of
excellence in their Stated and Implied sense. To achieve this objective, we dedicate ourselves to meet
the Challenges of becoming Visionary and Realistic, Sensitive and Demanding, Innovative and
Practical and Theoretical and Pragmatic; All at the same time"

VISION OF THE DEPARTMENT


To establish as a Center of Excellence in Education and Research in the field of Computer Science
& Engineering for transforming the students into Competent Professionals

MISSION OF THE DEPARTMENT


M1:Provide strong theoretical and practical background in Computer Science & Engineering and allied
fields of Engineering.
M2: Provide excellent state of the art infrastructure and competent man power to facilitate the need
based technical education to the students with ethical and social values.
M3: Encourage students to involve in Co-curricular and extracurricular activities.
M4: Promote Research and Innovation activities among the staff and students.

Python Programming Laboratory (24CSL46) 2 Semester IV


Department of Computer Science & Engineering

Program Educational Objectives (PEOs)


Computer Science Engineering graduates are able to
PEO1: Apply the knowledge of Engineering to solve construction related problems and involve in
research activities.
PEO2: Plan, design and execute the societal applications of Civil Engineering
PEO3: Involve effectively as a member or as a leader towards achieving goals in Civil Engineering
projects
PEO4: Engage in professional consultancy and continuous learning to accomplish professional
growth.
Program Outcomes (POs)
Engineering knowledge: Apply the knowledge of mathematics, science, engineering
PO1 fundamentals, and an engineering specialization to the solution of complex engineering
problems.
Problem analysis: Identify, formulate, research literature, and analyze complex engineering
PO2 problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
PO3
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
Conduct investigations of complex problems: Use research-based knowledge and research
PO4 methods including design of experiments, analysis and interpretation of data, and synthesis
of the information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
PO5 engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to assess
PO6 societal, health, safety, legal and cultural issues and the consequent responsibilities relevant
to the professional engineering practice.
Environment and sustainability: Understand the impact of the professional engineering
PO7 solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
PO8
norms of the engineering practice.
Individual and team work: Function effectively as an individual, and as a member or leader
PO9
in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with the
PO10 engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and

Python Programming Laboratory (24CSL46) 3 Semester IV


Department of Computer Science & Engineering

receive clear instructions.

Project management and finance: Demonstrate knowledge and understanding of the


PO11 engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
PO12 Life-long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.

Program Specific Outcomes (PSOs)


Utilize the Civil engineering knowledge and problem analysis skills to conceptualize,
PSO - 1
develop and execute the civil engineering projects.
Deploying quality Civil Engineers to work towards societal needs to achieve
PSO - 2
environmental and sustainable development.

Course Outcomes (COs):


At the end of the course the students will be able to:

Couse
Course Outcome
Index

C306.1 Demonstrate proficiency in handling of loops and creation of functions.


Identify the methods to create and manipulate lists, tuples and dictionaries.
C306.2
Discover the commonly used operations involving regular expressions and file
C306.3
system

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


Determine the need for scraping websites and working with PDF, JSON and other
C306.4
file formats.

Prepared By:………………………. Verified By:……………….

Approved By Head of the Department: ……………………..

Python Programming Laboratory (24CSL46) 4 Semester IV


Department of Computer Science & Engineering

Laboratory Programs
PART-A
List of problems for which student should develop program and execute in the Laboratory

1. 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.
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.
3. 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.
4. 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.
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 (sample@[Link]).
6. 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.
7. 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.
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.
Python Programming Laboratory(21CSL46) Semester IV
Department of Computer Science & Engineering

9. a) Write a python program to download the all XKCD comics b) Demonstrate python program
to read the data from the spreadsheet and write the data in to the spreadsheet
10. 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

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.

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

1 a) Write a python program to find the best of two test average marks out of three test’s
marks accepted from 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

1 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.

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 : 121
Palindrome
1 appears 2 times
Python Programming Laboratory(21CSL46) Semester IV
Department of Computer Science & Engineering

2 appears 1 times

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.
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")# Call the Fibonacci function and display the result or error message
result = F(n)
if result is not None:
print(f"The numbers till N are: {result}")
Output:
Enter a number : 5
fn(5) = 3

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

def bin2Dec(val):
rev=val[::-1]
dec = 0
i=0
for dig in rev:
dec += int(dig) * 2**i

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

i += 1
return dec
def oct2Hex(val):
rev=val[::-1]
dec = 0
i=0
for dig in rev:
dec += int(dig) * 8**i
i += 1
list=[]
while dec != 0:
[Link](dec%16)
dec = dec // 16

nl=[]
for elem in list[::-1]:
if elem <= 9:
[Link](str(elem))
else:
[Link](chr(ord('A') + (elem -10)))
hex = "".join(nl)
return hex
num1 = input("Enter a binary number : ")
print(bin2Dec(num1))
num2 = input("Enter a octal number : ")
print(oct2Hex(num2))
Output:
Enter a binary number : 10111001
185
Enter a octal number : 675
1BD

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

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

s = input("Enter a sentence: ")


w, d, u, l = 0, 0, 0, 0
l_w = [Link]()
w = len(l_w)
for c in s:
if [Link]():
d=d+1
elif [Link]():
u=u+1
elif [Link]():
l=l+1
print ("No of Words: ", w)
print ("No of Digits: ", d)
print ("No of Uppercase letters: ", u)
print ("No of Lowercase letters: ", l)

Output:
Enter a sentence : Rama went to Devaraja market to pick 2 kgs of vegetable
This sentence has 11 words
This sentence has 1 digits 2 upper case letters 42 lower case letters

3 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

import difflib
def string_similarity(str1, str2):
Python Programming Laboratory(21CSL46) Semester IV
Department of Computer Science & Engineering

result = [Link](a=[Link](), b=[Link]())


return [Link]()
str1 = 'Python Exercises'
str2 = 'Python Exercises'
print("Original string:")
print(str1)
print(str2)
print("Similarity between two said strings:")
print(string_similarity(str1,str2))
str1 = 'Python Exercises'
str2 = 'Python Exercise'
print("\nOriginal string:")
print(str1)
print(str2)
print("Similarity between two said strings:")
print(string_similarity(str1,str2))
Output:
Enter String 1
Python Exercises
Enter String 2
Python Exercises
Similarity between two said strings:
1.0

# Python3 code to demonstrate


# similarity between strings
# using naive method (sum() + zip())

# Utility function to compute similarity


def similar(str1, str2):
str1 = str1 + ' ' * (len(str2) - len(str1))
str2 = str2 + ' ' * (len(str1) - len(str2))
Python Programming Laboratory(21CSL46) Semester IV
Department of Computer Science & Engineering

return sum(1 if i == j else 0


for i, j in zip(str1, str2)) / float(len(str1))

# Initializing strings
test_string1 = 'Python Exerises'
test_string2 = ' Python Exerises''

# using naive method (sum() + zip())


# similarity between strings
res = similar(test_string1, test_string2)

# printing the result


print ("The similarity between 2 strings is : " + str(res))

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

import random
def merge_sort(lst):
if len(lst) > 1:
mid = len(lst) // 2
left_half = lst[:mid]
right_half = lst[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]:
lst[k] = left_half[i]
i += 1
else:
lst[k] = right_half[j]
j += 1

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

k += 1
while i < len(left_half):
lst[k] = left_half[i]
i += 1
k += 1
while j < len(right_half):
lst[k] = right_half[j]
j += 1
k += 1
return lst
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
my_list = []
for i in range(10):
my_list.append([Link](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(10):
my_list.append([Link](0, 999))
print("\nUnsorted List")
print(my_list)
print("Sorting using Merge Sort")

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

merge_sort(my_list)
print(my_list)
Output:
Unsorted List
[932, 111, 226, 685, 543, 589, 918, 539, 294, 717]
Sorting using Insertion Sort
[111, 226, 294, 539, 543, 589, 685, 717, 918, 932]
Unsorted List
[613, 176, 828, 265, 65, 326, 359, 919, 514, 868]
Sorting using Merge Sort
[65, 176, 265, 326, 359, 514, 613, 828, 868, 919]

4 b) Write a program to convert roman numbers in to integer values using dictionaries .

def roman2Dec(romStr):
roman_dict ={'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
# Analyze string backwards
romanBack = list(romStr)[::-1]
value = 0
# To keep track of order
rightVal = roman_dict[romanBack[0]]
for numeral in romanBack:
leftVal = roman_dict[numeral]
# Check for subtraction
if leftVal < rightVal:
value -= leftVal
else:
value += leftVal
rightVal = leftVal
return value
romanStr = input("Enter a Roman Number : ")
print(roman2Dec(romanStr))

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

Output:
Enter a Roman Number : XVII
17
Enter a Roman Number : MLXVI
1066

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.
import re
def isphonenumber(numStr):
if len(numStr) != 12:
return False
for i in range(len(numStr)):
if i==3 or i==7:
if numStr[i] != "-":
return False
else:
if numStr[i].isdigit() == False:
return False
return True

def chkphonenumber(numStr):
ph_no_pattern = [Link](r'^\d{3}-\d{3}-\d{4}$')
if ph_no_pattern.match(numStr):
return True
else:
return False
ph_num = input("Enter a phone number : ")
print("Without using Regular Expression")
if isphonenumber(ph_num):
print("Valid phone number")

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

else:
print("Invalid phone number")

print("Using Regular Expression")


if chkphonenumber(ph_num):
print("Valid phone number")
else:
print("Invalid phone number")
Output:
Enter a phone number : 444-654-5656
Without using Regular Expression
Valid phone number
Using Regular Expression
Valid phone number

5 b). Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses (sample@[Link])
import re
# Define the regular expression for phone numbers
phone_regex = [Link](r'\+\d{12}')
email_regex = [Link](r'[A-Za-z0-9._]+@[A-Za-z0-9]+\.[A-Z|a-z]{2,}')
# Open the file for reading
with open('[Link]', '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)

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

matches = email_regex.findall(line)
# Print any matches found
for match in matches:
print(match)
Output:
+918151894220
+829392938876
+918768456234
prakash81.82@[Link]

6 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
import [Link]

import sys

fname = input("Enter the filename : ")

if not [Link](fname):

print("File", fname, "doesn't exists")

[Link](0)

infile = open(fname, "r")

lineList = [Link]()

for i in range(20):

print(i+1, ":", lineList[i])

word = input("Enter a word : ")

cnt = 0

for line in lineList:

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

cnt += [Link](word)

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

Output:

Enter the filename : [Link]

1 : this is phone number +918151894220

2 : no phone number here

3 : here we have one +829392938876

4 : we have an email prakash81.82@[Link] and a number +918768456234

5 : nothing of that sort here

6 : Better hope the life-inspector doesn't come around while you have your

7 : life in such a mess.

8 : You can create your own opportunities this week. Blackmail a senior executive.

9 : Be different: conform.

10 : Be cheerful while you are alive.

11 : -- Phathotep, 24th Century B.C.

12 : Q: How many journalists does it take to screw in a light bulb?

13 : A: Three. One to report it as an inspired government program to bring

14 : light to the people, one to report it as a diabolical government plot

15 : to deprive the poor of darkness, and one to win a Pulitzer prize for

16 : reporting that Electric Company hired a light bulb-assassin to break

17 : the bulb in the first place.

18 : Q: Why did the astrophysicist order three hamburgers?

19 : A: Because he was hungry.

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

20 : Q: Why haven't you graduated yet?

Enter a word : the

The word the appears 7 times in the file

6 b). Write a python program to create a zip of a particular folder which contains

several files inside it.

import os
from zipfile import ZipFile

# Create a ZipFile Object


with ZipFile('G:\\cse4_zip_file.zip', 'w') as zip_object:
# Adding files that need to be zipped
zip_object.write('G:\\cse4_zip_file\\[Link]')
zip_object.write('G:\\cse4_zip_file\\[Link]')

# Check to see if the zip file is created


if [Link]('G:\\cse4_zip_file.zip'):
print("ZIP file created")
else:
print("ZIP file not created")
Output:

Zip file created

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

7. a). By using the concept of inheritance write a python program to find the area of triangle,
circle and rectangle.
import math
class Shape:
def __init__(self):
[Link] = 0
[Link] = ""

def showArea(self):
print("The area of the", [Link], "is", [Link], "units")

class Circle(Shape):
def __init__(self,radius):
[Link] = 0
[Link] = "Circle"
[Link] = radius

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

def calcArea(self):
[Link] = [Link] * [Link] * [Link]

class Rectangle(Shape):
def __init__(self,length,breadth):
[Link] = 0
[Link] = "Rectangle"
[Link] = length
[Link] = breadth

def calcArea(self):
[Link] = [Link] * [Link]

class Triangle(Shape):
def __init__(self,base,height):
[Link] = 0
[Link] = "Triangle"
[Link] = base
[Link] = height

def calcArea(self):
[Link] = [Link] * [Link] / 2

c1 = Circle(5)
[Link]()
[Link]()
r1 = Rectangle(5, 4)
[Link]()
[Link]()

t1 = Triangle(3, 4)

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

[Link]()
[Link]()
Output:
the area of the Circle is 113.09733552923255 units
the area of the Rectangle is 210 units
the area of the Triangle is 91.0 units

7. b). 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.
class Employee:
def __init__(self):
[Link] = ""
[Link] = ""
[Link] = ""
[Link] = 0

def getEmpDetails(self):
[Link] = input("Enter Employee name : ")
[Link] = input("Enter Employee ID : ")
[Link] = input("Enter Employee Dept : ")
[Link] = int(input("Enter Employee Salary : "))

def showEmpDetails(self):
print("Employee Details")
print("Name : ", [Link])
print("ID : ", [Link])
print("Dept : ", [Link])
print("Salary : ", [Link])

def updtSalary(self):
[Link] = int(input("Enter new Salary : "))

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

print("Updated Salary", [Link])

e1 = Employee()
[Link]()
[Link]()
[Link]()
Output:-
Enter Employee name :Ramu
Enter Employee ID :986
Enter Employee Dept :cse
Enter Employee Salary :120000
Employee Details
Name : Ramu
ID : 986
Dept : cse
Enter new Salary : 13000
Updated Salary 13000

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.
class PaliStr:
def __init__(self):
[Link] = False

def chkPalindrome(self, myStr):


if myStr == myStr[::-1]:
[Link] = True
else:
[Link] = False

return [Link]
Python Programming Laboratory(21CSL46) Semester IV
Department of Computer Science & Engineering

class PaliInt(PaliStr):
def __init__(self):
[Link] = False

def chkPalindrome(self, val):


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

if val == rev:
[Link] = True
else:
[Link] = False

return [Link]
st = input("Enter a string : ")
stObj = PaliStr()
if [Link](st):
print("Given string is a Palindrome")
else:
print("Given string is not a Palindrome")
val = int(input("Enter a integer : "))
intObj = PaliInt()
if [Link](val):
print("Given integer is a Palindrome")
else:
print("Given integer is not a Palindrome")

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

Output:
Enter a string : madam
Given string is a Palindrome
Enter a integer : 121
Given integer is a Palindrome

Enter a string : Ramu


Given string is not a Palindrome
Enter a integer : 123
Given integer is not a Palindrome

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


import requests, os, bs4
url = '[Link] # starting url
[Link]('xkcd',exist_ok = True) # create a directory to store all the downloads

while not [Link]("#"):


# Download the page.
print("Downloading the page ... ")
res = [Link](url)
res.raise_for_status()
try:
soup = [Link]([Link],'lxml')
except [Link]: # lxml is not installed
soup = [Link]([Link],'[Link]')

# Find the URL of the comic image.


comic_element = [Link]('#comic img')
if comic_element == []:
print("No comic image found!!..")
else:
comic_image_url = comic_element[0].get('src')

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

# download the image


print("Downloading the image %s .. " %(comic_image_url))
res = [Link]('http:' + comic_image_url)
res.raise_for_status()

# Save the image to ./xkcd.


file = open( [Link]('xkcd',[Link](comic_image_url)) , 'wb')
for chunk in res.iter_content(10000):
[Link](chunk)
[Link]()

# Get the Prev button's url.


prev_link = [Link]('a[rel="prev"]')[0]
url = '[Link] + prev_link.get('href')

print("Done")

Output:

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

from openpyxl import Workbook

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

from [Link] import PatternFill

wb=openpyxl.load_workbook('student_4cse3.xlsx') #opening the student_4cse3.xlsx


file sh1=wb['Marks_Test1'] # assign the sheet name ‘sheet name Marks_Test1’ to
sh1
row =sh1.max_row
column = sh1.max_column
for i in range(1,row+1):
for j in range(1,column+1):
print([Link](i,j).value)

[Link](row=5,column=1,value='MT21CS135')
sh1['A5'].fill=PatternFill("solid",fgColor="71FF33")
[Link](row=5,column=2,value='sathvik')
sh1['B5'].fill=PatternFill("solid",fgColor="71FF33")
[Link](row=5,column=3,value='20')
sh1['C5'].fill=PatternFill("solid",fgColor="71FF33")
[Link](row=5,column=4,value='16')
sh1['D5'].fill=PatternFill("solid",fgColor="71FF33")
[Link]('[Link]') # creates new xlsx file with old and new data in a new
filename
Output:

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

10 a). 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('[Link]', 'rb')


pdf2 = open('[Link]', '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('[Link]', 'wb') as output:


pdf_writer.write(output)

Output:

[Link] [Link]

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

[Link]

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

import requests, json

api_key = "980fc61e5f43515a2ec709c871aa6b70"

base_url = "[Link]
city_name = input("Enter city name : ")

complete_url = base_url + "appid=" + api_key + "&q=" + city_name

response = [Link](complete_url)
x = [Link]()
if x["cod"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_pressure = y["pressure"]
current_humidity = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]

Python Programming Laboratory(21CSL46) Semester IV


Department of Computer Science & Engineering

# print following values


print(" Temperature (in kelvin unit) = " + str(current_temperature) +
"\n atmospheric pressure (in hPa unit) = " + str(current_pressure) +
"\n humidity (in percentage) = " + str(current_humidity) +
"\n description = " + str(weather_description))
else:
print(" City Not Found ")

Output:

Enter city name : Mangalore


Temperature (in kelvin unit) = 302.63
atmospheric pressure (in hPa unit) = 1011
humidity (in percentage) = 74
description = scattered clouds

Python Programming Laboratory(21CSL46) Semester IV

Common questions

Powered by AI

The Python Programming Laboratory course prepares students to handle real-world data manipulation and analysis tasks through a curriculum that emphasizes hands-on programming experiences. Students learn to implement data structures such as lists, tuples, and dictionaries, and perform operations like sorting and searching . They are also trained to use regular expressions for data extraction and file manipulation techniques, which are crucial for real-world data analysis tasks like web scraping and handling file formats like PDF and JSON . This practical training equips students with the skills necessary to analyze and process data effectively in professional settings.

The Python Programming Laboratory at MITE fosters problem analysis skills by engaging students in practical coding tasks that require breaking down complex problems into manageable parts. Course outcomes include demonstrating proficiency in loops and function creation, and manipulating data structures like lists, tuples, and dictionaries . Additionally, students are tasked with developing algorithms and executing programs for given problems, which enhances their ability to identify, formulate, and analyze issues systematically, thus aligning with PO2 that focuses on problem analysis .

The Python Programming Laboratory course at MITE integrates core programming concepts through structured lab exercises that cover loops, functions, data structures, and object-oriented programming . These exercises are designed to cement students' understanding of programming logic and syntax. Practical application is ensured by involving students in tasks like developing algorithms, writing scripts for data manipulation, and implementing sorting methods . This combination of theory and hands-on practice prepares students to tackle real-world coding challenges, aligning with the course outcomes that emphasize both proficiency in programming and the manipulation of various data types .

Ethical and social values are integral to the technical education at MITE's Computer Science & Engineering department. M2 of the department's mission emphasizes technical education with ethical and social values. PO8 further reinforces this by promoting ethical principles and a commitment to professional responsibilities, ensuring that graduates not only possess technical skills but also a moral framework for their application . This approach ensures that students understand their professional responsibilities, assess societal issues, and integrate sustainable and ethical practices into their engineering solutions, contributing positively to society .

The PEOs at MITE aim to apply engineering knowledge to solve real-world problems, engage in professional practice, and encourage continuous learning, which aligns with the broader goals of equipping students with practical problem-solving skills and a foundation for lifelong learning . The POs further complement these goals by emphasizing the application of engineering fundamentals, problem analysis, design and development of solutions, research-based knowledge application, and use of modern tools, mirroring broader educational objectives of producing competent, ethical engineers capable of addressing complex societal and technical challenges .

At MITE, ethics and sustainability are integral to the learning outcomes for engineering students. PO8 emphasizes the application of ethical principles and commitment to professional ethics and norms, which is crucial for responsible engineering practice . Moreover, PO7 focuses on understanding the societal and environmental impact of engineering solutions, highlighting the importance of sustainable development. These elements ensure that students are not only skilled in technical aspects but also sensitive to ethical considerations and the need for sustainability, reflecting the institution’s commitment to holistic engineering education .

Lifelong learning is a cornerstone of MITE's educational framework, emphasizing the importance of adaptability and continuous development in the face of technological change. PO12 specifically addresses the recognition of the need for independent and continuous learning, preparing students to stay abreast of technological advancements and apply new knowledge throughout their careers . This priority is integrated into the curriculum through project-based learning, research activities, and updated course content to encourage a mindset of ongoing education and skill enhancement .

MITE promotes research and innovation in the Computer Science & Engineering department through targeted mission directives such as M4, which explicitly aims to foster research and innovative activities among students and staff . This includes providing state-of-the-art infrastructure and resources, encouraging participation in research projects, and hosting workshops and seminars to spur creative thinking. The institution also supports co-curricular activities and collaboration with industries and research organizations to enhance the practical application of theoretical knowledge .

MITE employs several educational strategies to prepare students for leadership roles in engineering projects. This includes fostering teamwork and communication skills as highlighted by PO9 and PO10, which ensure students can effectively work in and lead diverse teams . The curriculum includes project-based learning, encouraging students to manage real-world projects from concept to execution. PEO3 is aimed at developing leadership competencies required to meet engineering project goals. Furthermore, MITE promotes lifelong learning and continuous professional development, equipping students with the adaptability and knowledge necessary for leadership in a rapidly evolving field .

The vision of Mangalore Institute of Technology & Engineering (MITE) is to provide globally competitive quality education while contributing to the global community through research and development . This relates to its educational approach by emphasizing a combination of theoretical and practical knowledge, ensuring that students receive quality education aligned with global standards. The mission supports the establishment of world-class educational institutions that aim for excellence, pushing students to meet challenges through innovative, theoretical, and pragmatic methods. Quality assurance is maintained through accreditations from NAAC and NBA, and certification under ISO 9001: 2015, which signifies adherence to internationally recognized quality standards .

You might also like