PYTHON PROGRAMMING LABORATORY – 21CSL46

In this blog post, you will find solutions for the PYTHON PROGRAMMING LABORATORY (21CSL46) course work for the IV semester of VTU university. To follow along, you will need to set up a Python programming environment. We recommend using the Anaconda Python Distribution with Spyder as the integrated development environment (IDE). You can find the lab syllabus on the university’s website or click here.

For detailed instructions on setting up the Python programming environment on Ubuntu, please refer to my previous blog, which can be found below.

Setting up Anaconda Python Programming Environment on Ubuntu

If you are looking for step-by-step instructions on how to set up the Python programming environment on a Windows system, I have provided detailed guidance in my previous blog. You can access the blog below for all the information you need.

All these solutions have been maintained at the following git repository shown below. If you want to contribute send me a PR.

https://gitlab.com/lab_manuals/21csl46pyprlab_vtu

After getting the necessary development environment setup, Now lets focus on the solutions.

  1. Question 1
    1. Test Average
    2. Palindrome
  2. Question 2
    1. Fibonacci Sequence
    2. Base Conversion
  3. Question 3
    1. Sentence statistics
    2. String Similarity
  4. Question 4
    1. Insertion Sort & Merge Sort
    2. Convert Roman numbers in to Integer
  5. Question 5
    1. Check Phone Number
    2. Search Phone Number & Email
  6. Question 6
    1. File Operations
    2. Zip operation on a folder
  7. Question 7
    1. Inheritance
    2. Employee Details
  8. Question 8
    1. Polymorphism and Inheritance
  9. Question 9
    1. Download XKCD comics
    2. Spreadsheet Operations
  10. Question 10
    1. Merge selected pages from Multiple PDFs to a new PDF
    2. Fetch weather data from the JSON

Question 1

Calculation of Test Average

Write a python program to find the best of two test average marks out of three test’s marks accepted from the user.

Python Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 21 16:27:47 2023

@author: Prabodh C P
"""

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    

best_of_two = sorted([m1, m2, m3], reverse=True)[:2]
average_best_of_two = sum(best_of_two)/2
    
print("Average of best two test marks out of three test’s marks is", average_best_of_two);

The provided Python program is designed to calculate the average of the best two test marks out of three. The user is prompted to input the marks for three tests (test1, test2, and test3). The program then identifies the two highest test marks using the sorted function in descending order and selects the top two values. Finally, it calculates the average of these two highest marks and prints the result. This code is a concise way to determine the average performance based on the two best test scores out of three.

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

Palindrome Check & Digit Occurrence Count

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.

Python Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 21 16:35:54 2023

@author: Prabodh C P
"""

from collections import Counter

value = input("Enter a value : ")
if value == value[::-1]:
    print("Palindrome")
else:
    print("Not Palindrome")
    
counted_dict = Counter(value)
for key in sorted(counted_dict.keys()):
    print(f'{key} appears {counted_dict[key]} times');

"""
#Alternate way to count appearances
for i in range(10):
    if value.count(str(i)) > 0:
        print(f'{str(i)} appears {value.count(str(i))} times')
"""

The provided Python script is a versatile program that performs two key tasks: palindrome checking and character counting.

  1. Palindrome Check:
    • The user is prompted to input a value.
    • The script determines whether the entered value is a palindrome, meaning it reads the same backward as forward.
    • If the input is a palindrome, it prints “Palindrome”; otherwise, it prints “Not Palindrome.”
  2. Character Count:
    • The script utilizes the Counter class from the collections module to efficiently count the occurrences of each character in the input string.
    • It then sorts the keys of the counted dictionary and prints each character along with the number of times it appears.
  3. Alternate Character Count (commented-out):
    • The script provides an alternative method using a loop to count the occurrences of each digit (0 to 9) in the input string.

This script is not only a quick and effective way to check for palindromes but also serves as a handy tool for analyzing the frequency of characters in a given input. The inclusion of alternative methods showcases the flexibility of the script, making it a valuable resource for both palindrome detection and character frequency analysis.

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

Question 2

Fibonacci Sequence

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.

Python Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 21 16:46:55 2023

@author: Prabodh C P
"""

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

try:
    num = int(input("Enter a number : "))
    if num > 0:
        print(f' fn({num}) = {fn(num)}')
    else:
        print("Input should be greater than 0")
except ValueError:
    print("Try with numeric value")

The provided Python script introduces a recursive implementation to calculate terms in the Fibonacci sequence. Here’s a concise overview:

  1. Recursive Fibonacci Function:
    • The script defines a function fn that calculates the nth term in the Fibonacci sequence.
    • If the input n is 1 or 2, the function returns n - 1.
    • For n greater than 2, the function recursively calls itself with n-1 and n-2 and returns the sum of the results.
  2. User Input and Output:
    • The user is prompted to enter a number.
    • If a positive integer is provided, the script prints the result of calling the fn function with that number, representing the nth term in the Fibonacci sequence.
    • If the entered value is not a positive integer, it prompts the user to enter a value greater than 0.
    • If a non-numeric value is entered, it catches the ValueError and suggests trying with a numeric value.

This script serves as a simple yet illustrative example of a recursive function for computing Fibonacci sequence terms, offering insights into recursive algorithms and user input handling in Python.

Output

Enter a number : 5
fn(5) = 3
Enter a number: -3
Input should be greater than 0
Enter a number: abc
Try with numeric value

Binary to Decimal & Octal to Hexadecimal Conversion

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

Python Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 21 20:57:52 2023

@author: Prabodh C P
"""

"""
def bin2Dec(val):
    rev=val[::-1]
    dec = 0
    i = 0
    for dig in rev:
        dec += int(dig) * 2**i
        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:
        list.append(dec%16)
        dec = dec // 16
        
    nl=[]
    for elem in list[::-1]:
        if elem <= 9:
            nl.append(str(elem))
        else:
            nl.append(chr(ord('A') + (elem -10)))
    hex = "".join(nl)
    
    return hex


base = 2
num1 = input("Enter a binary number : ")    
# print(bin2Dec(num1))
print(int(num1, base))
"""

#A better implementation
def bin2Dec(val):
    return int(val, 2)
    
def oct2Hex(val):
    return int(val, 8)

try:
    num1 = input("Enter a binary number : ")    
    print(bin2Dec(num1))
except ValueError:
    print("Invalid literal in input with base 2")
    
try:
    num2 = input("Enter a octal number : ")
    print(oct2Hex(num2))
except ValueError:
    print("Invalid literal in input with base 8")

This Python script includes two functions bin2Dec and oct2Hex for converting binary to decimal and octal to hexadecimal, respectively. The script takes user input for binary and octal numbers and converts them using these functions. Here’s a brief description:

  1. Conversion Functions:
    • The bin2Dec function converts a binary number to decimal using the int() function with base 2.
    • The oct2Hex function converts an octal number to hexadecimal using the int() function with base 8.
  2. User Input Handling:
    • The script includes try-except blocks to catch ValueError in case of invalid input.
    • It prompts the user for a binary and an octal number, converts them, and prints the results.
    • If an invalid input is detected, it prints an error message.

Output

Enter a binary number: 101010
42

Enter an octal number: 755
0x1FD

Enter a binary number: 11011a
Invalid literal in input with base 2

Enter an octal number: 1298
Invalid literal in input with base 8

Question 3

Sentence Statistics

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

Python Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 22 01:37:07 2023

@author: Prabodh C P
"""

import string

sentence = input("Enter a sentence : ")

wordList = sentence.strip().split(" ")
print(f'This sentence has {len(wordList)} words', end='\n\n')

digit_count = uppercase_count = lowercase_count = 0

"""
for ch in sentence:
    if '0' <= ch <= '9':
        digit_count += 1
    elif 'A' <= ch <= 'Z':
        uppercase_count += 1
    elif 'a' <= ch <= 'z':
        lowercase_count += 1
"""

for character in sentence:
    if character in string.digits: 
        digit_count += 1
    elif character in string.ascii_uppercase: 
        uppercase_count += 1
    elif character in string.ascii_lowercase:
        lowercase_count += 1

print(f'This sentence has {digit_count} digits',
      f' {uppercase_count} upper case letters',
      f' {lowercase_count} lower case letters', sep='\n')

The above Python program is designed to analyse a user-inputted sentence, providing information on the number of words, digits, uppercase letters, and lowercase letters in the given text. Here’s a concise overview:

  1. Word Count:
    • The script splits the input sentence into words and prints the count of words in the sentence.
  2. Character Analysis:
    • It then iterates through each character in the sentence.
    • The script counts the number of digits, uppercase letters, and lowercase letters using the string module.
  3. Print Results:
    • Finally, it prints the counts of digits, uppercase letters, and lowercase letters in the given sentence.

This script serves as a versatile tool for quickly extracting key statistics from a user-provided sentence, offering insights into the composition of the text in terms of words and character types.

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

String Similarity

Write a Python program to find the string similarity between two given strings.

Python Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 22 01:48:17 2023

@author: Prabodh C P
"""

"""
str1 = input("Enter String 1 \n").lower()
str2 = input("Enter String 2 \n").lower()

# if len(str2) < len(str1):
#     short = len(str2)
#     long = len(str1)
# else:
#     short = len(str1)
#     long = len(str2)

string_1_length = len(str1)
string_2_length = len(str2)

short_string_length, long_string_length = min(string_1_length, string_2_length), max(string_1_length, string_2_length) 
    

match_count = 0
for i in range(short_string_length):
    if str1[i] == str2[i]:
        match_count += 1

print("Similarity between two said strings:")
print(match_count/long_string_length)


"""
# An alternative solution to the same problem using Python libraries

from difflib import SequenceMatcher

str1 = input("Enter String 1 : ")
str2 = input("Enter String 2 : ")

sim = SequenceMatcher(None, str1, str2).ratio()

print("Similarity between strings \"" + str1 + "\" and \"" + str2 + "\" is : ",sim)

The provided Python script is designed to compare the similarity between two user-inputted strings. The user is prompted to input two strings, and the script, after converting them to lowercase for case-insensitive comparison, calculates the similarity by counting the matching characters at corresponding positions. The similarity is then expressed as a ratio relative to the length of the longer string. Here’s a brief overview:

  1. User Input:
    • The script prompts the user to enter two strings.
  2. String Comparison:
    • The script then iterates through characters at corresponding positions and counts the matches.
  3. Similarity Ratio:
    • The similarity between the two strings is calculated as the ratio of the count of matching characters to the length of the longer string.
  4. Alternative Solution :
    • The script includes an alternative solution using the SequenceMatcher class from the difflib library, demonstrating a different approach to calculating string similarity.

This script offers a straightforward way to measure the similarity between two strings and presents an alternative solution using Python libraries for a comparative understanding. It’s a useful tool for users interested in comparing the likeness of textual data.

Output

Enter String 1 : Python Exercises
Enter String 2 : Python Exercise 
Similarity between strings "Python Exercises" and "Python Exercise" is :  0.967741935483871
Enter String 1 : Python Exercises
Enter String 2 : Python Exercises
Similarity between strings "Python Exercises" and "Python Exercises" is :  1.0

Question 4

Insertion Sort & Merge Sort on lists

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

Python Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar  9 04:06:09 2023

@author: Prabodh C P
"""

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

This Python program demonstrates two popular sorting algorithms: Insertion Sort and Merge Sort. The code begins by generating a random list of integers. First, it applies the Insertion Sort algorithm to sort the list in ascending order. Then, it generates a new random list and applies the Merge Sort algorithm to achieve the same result.

  1. Insertion Sort:
    • The insertion_sort function implements the Insertion Sort algorithm, which iterates through the list and places each element in its correct position relative to the elements before it.
    • The program generates a random list, prints the unsorted list, applies Insertion Sort, and prints the sorted list.
  2. Merge Sort:
    • The merge_sort function implements the Merge Sort algorithm, a divide-and-conquer approach that recursively divides the list into halves until individual elements are reached, then merges them in a sorted manner.
    • The program generates another random list, prints the unsorted list, applies Merge Sort, and prints the sorted list.

The code showcases the functionality of these sorting algorithms and provides insights into their working mechanisms.

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]

Roman to Integer Conversion

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.

Python Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 22 02:05:25 2023

@author: Prabodh C P
"""


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("Equivalent Decimal number :",roman2Dec(romanStr))

This Python program, converts a Roman numeral string to its corresponding decimal value. The core function, roman2Dec, utilizes a dictionary to map Roman numerals to their decimal equivalents. The program prompts the user to input a Roman numeral, and it then applies the conversion function and prints the resulting decimal value.

  1. Conversion Function:
    • The roman2Dec function takes a Roman numeral string as input and iterates through it in reverse order.
    • It uses a dictionary, roman_dict, to map each Roman numeral to its corresponding decimal value.
    • The function calculates the decimal value by comparing the current numeral with the one on its right, determining whether to add or subtract its value accordingly.This code provides a simple and effective way to convert Roman numerals to decimal form, demonstrating the use of dictionaries for efficient mapping.

This code provides a simple and effective way to convert Roman numerals to decimal form, demonstrating the use of dictionaries for efficient mapping.

Output

Enter a Roman Number : XVII
Equivalent Decimal number : 17

Enter a Roman Number : MLXVI
Equivalent Decimal number : 1066

Question 5

Check Phone Number

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.

Python Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar  9 04:19:57 2023

@author: Prabodh C P
"""
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 = re.compile(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")
else:
    print("Invalid phone number")

print("Using Regular Expression")
if chkphonenumber(ph_num):
    print("Valid phone number")
else:
    print("Invalid phone number")

This Python program, designed to validate phone numbers, provides two different approaches: one without using regular expressions and another using regular expressions.

  1. Non-Regular Expression Approach (isphonenumber function):
    • The isphonenumber function checks if a given phone number string is valid without using regular expressions.
    • It verifies that the length of the string is 12 characters and that the characters at positions 3 and 7 are hyphens.
    • It further checks that the remaining characters are digits.
  2. Regular Expression Approach (chkphonenumber function):
    • The chkphonenumber function uses a regular expression to validate phone numbers.
    • It employs the re.compile function to create a regular expression pattern (^\d{3}-\d{3}-\d{4}$).
    • The pattern ensures that the phone number follows the format of three digits, a hyphen, three digits, another hyphen, and four digits.
  3. User Input and Output:
    • The program prompts the user to input a phone number.
    • It then calls both validation functions and prints whether the phone number is valid or invalid for each approach.

This program demonstrates two distinct methods for validating phone numbers—one based on manual character checks and the other utilizing the power of regular expressions for a more concise and flexible solution.

Output

Enter a phone number : 444-654-5656
Without using Regular Expression
Valid phone number
Using Regular Expression
Valid phone number
Enter a phone number : 45A4-444-878
Without using Regular Expression
Invalid phone number
Using Regular Expression
Invalid phone number

Search Phone Number & Email

Develop a python program that could search the text in a file for phone numbers (+919900889977) and email addresses (sample@gmail.com)

Python Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar  9 04:40:10 2023

@author: Prabodh C P
"""

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)            

This Python program employs regular expressions to extract and print phone numbers and email addresses from a given text file (example.txt). Here’s a brief description:

  1. Regular Expressions:
    • The program uses two regular expressions:
      • phone_regex: Designed to match international phone numbers in the format ‘+XXXXXXXXXXXX’ where ‘X’ represents digits.
      • email_regex: Crafted to identify email addresses following the standard email format.
  2. File Reading:
    • The program opens the file ‘example.txt’ for reading using a context manager (with open('example.txt', 'r') as f).
  3. Line Processing:
    • It iterates through each line in the file (for line in f:).
    • For each line, it searches for matches using both regular expressions.
  4. Printing Matches:
    • The program prints any phone numbers and email addresses found in the file.
    • Matches are printed line by line, providing a clear output.
  5. Usage:
    • Users can replace ‘example.txt’ with the path to their desired text file containing phone numbers and email addresses.

This program serves as a handy tool for extracting and analyzing phone numbers and email addresses from text files, demonstrating the efficiency and flexibility of regular expressions in text pattern matching.

Output

+918151894220
+829392938876
+918768456234
prakash81.82@gmail.in

Question 6

File Operations

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

Python Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar  9 05:26:33 2023

@author: Prabodh C P
"""

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

lineList = infile.readlines()

lineCount = int(input("Enter the number of lines you want to display : "))
for i in range(lineCount):
    print(i+1, ":", lineList[i], end="")
    
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")

This Python program is designed to analyze a text file. Here’s a brief description:

  1. File Existence Check:
    • The program prompts the user to input a filename (fname).
    • It checks whether the specified file exists using os.path.isfile(fname).
  2. File Opening:
    • If the file exists, it opens the file (infile = open(fname, "r")) for reading.
  3. Reading Lines:
    • The program reads all lines from the file and stores them in a list (lineList = infile.readlines()).
  4. Displaying Initial Lines:
    • It prints the first 20 lines of the file, numbered from 1 to 20.
  5. Word Count:
    • The program then prompts the user to input a word (word).
    • It counts the occurrences of the specified word in the entire file.
  6. Output:
    • The program prints the count of occurrences of the specified word in the file.

This program provides a quick overview of the content of a text file, allowing users to inspect the initial lines and find the frequency of a specific word within the file. It is a useful tool for preliminary text analysis.

Output

Enter the filename :  example.txt
Enter the number of lines you want to display :  6
1 : this is phone number +918151894220
2 : no phone number here
3 : here we have one +829392938876
4 : we have an email prakash81.82@gmail.in and a number +918768456234 
5 : nothing of that sort here
6 : Better hope the life-inspector doesn't come around while you have your
Enter a word :  Why
The word Why appears 2 times in the file

Zip operation on a folder

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 Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 23 16:14:28 2022

@author: Prabodh C P
"""

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)
    
with zipfile.ZipFile("myZip.zip", mode="w") as archive:
    for file_path in curDirectory.rglob("*"):
        archive.write(file_path, arcname=file_path.relative_to(curDirectory))
    
if os.path.isfile("myZip.zip"):
    print("Archive", "myZip.zip", "created successfully")
else:
    print("Error in creating zip archive")

This Python program is designed to create a backup of a directory by compressing its contents into a zip file. Here’s a brief description:

  1. Directory Existence Check:
    • The program prompts the user to input a directory name (dirName).
    • It checks whether the specified directory exists using os.path.isdir(dirName).
  2. Directory Path Setup:
    • If the directory exists, it creates a pathlib.Path object (curDirectory) representing the specified directory.
  3. Zip File Creation:
    • The program uses the zipfile module to create a zip file named “myZip.zip” (with zipfile.ZipFile("myZip.zip", mode="w") as archive).
    • It iterates through all files in the specified directory and its subdirectories using curDirectory.rglob("*").
    • For each file, it adds the file to the zip archive, preserving the directory structure within the archive (archive.write(file_path, arcname=file_path.relative_to(curDirectory))).
  4. Output:
    • If the zip file “myZip.zip” is successfully created, it prints a success message.
    • If there’s an issue creating the zip archive, it prints an error message.

This program is a simple and effective way to create a compressed backup of a directory, making it easier to store and transfer a set of files and directories.

Output

Enter Directory name that you want to backup : zipDemo
Archive myZip.zip created successfully

Question 7

Inheritance

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

Python Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar  9 05:40:37 2023

@author: Prabodh C P
"""

import math

class Shape:
    def __init__(self):
        self.area = 0
        self.name = ""
        
    def showArea(self):
        print("The area of the", self.name, "is", self.area, "units")
        
class Circle(Shape):
    def __init__(self,radius):
        self.area = 0
        self.name = "Circle"
        self.radius = radius
        
    def calcArea(self):
        self.area = math.pi * self.radius * self.radius
    
class Rectangle(Shape):
    def __init__(self,length,breadth):
        self.area = 0
        self.name = "Rectangle"
        self.length = length
        self.breadth = breadth
        
    def calcArea(self):
        self.area = self.length * self.breadth

class Triangle(Shape):
    def __init__(self,base,height):
        self.area = 0
        self.name = "Triangle"
        self.base = base
        self.height = height
        
    def calcArea(self):
        self.area = self.base * self.height / 2
    

    
c1 = Circle(5)
c1.calcArea()
c1.showArea()


r1 = Rectangle(5, 4)
r1.calcArea()
r1.showArea()


t1 = Triangle(3, 4)
t1.calcArea()
t1.showArea()

This Python program defines a simple object-oriented system to calculate and display the area of different geometric shapes. Here’s a brief description:

  1. Shape Class:
    • The Shape class serves as the base class for geometric shapes. It has an __init__ method to initialize the area and name, and a showArea method to display the area.
  2. Circle, Rectangle, and Triangle Classes:
    • These classes (Circle, Rectangle, and Triangle) inherit from the Shape class.
    • Each shape class has its own __init__ method to set specific attributes like radius, length, and breadth.
    • Each shape class has a calcArea method to calculate the area based on its specific formula.
  3. Example Instances:
    • The program creates instances of each shape class (c1, r1, and t1).
    • For each instance, it calls the calcArea method to calculate the area.
    • Finally, it calls the showArea method to display the area for each shape.
  4. Output:
    • The program outputs the calculated areas for a circle, rectangle, and triangle.

This program demonstrates basic principles of object-oriented programming (OOP) by using inheritance and encapsulation to model different shapes and their respective areas. It provides a clear structure for extending the system to include additional shapes in the future.

Output

The area of the Circle is 78.53981633974483 units
The area of the Rectangle is 20 units
The area of the Triangle is 6.0 units

Employee Details

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.

Python Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar  9 12:09:50 2023

@author: Prabodh C P
"""

class Employee:
    def __init__(self):
        self.name = ""
        self.empId = ""
        self.dept = ""
        self.salary = 0
        
    def getEmpDetails(self):
        self.name = input("Enter Employee name : ")
        self.empId = input("Enter Employee ID : ")
        self.dept = input("Enter Employee Dept : ")
        self.salary = int(input("Enter Employee Salary : "))
        
    def showEmpDetails(self):
        print("Employee Details")
        print("Name : ", self.name)
        print("ID : ", self.empId)
        print("Dept : ", self.dept)
        print("Salary : ", self.salary)
        
    def updtSalary(self, hike):
        self.salary += self.salary*hike/100
        print("Updated Salary for",self.name)
        
company = []
def main():
    for i in range(5):
        e1 = Employee()
        e1.getEmpDetails()
        company.append(e1)

    print("\nEMPLOYEE DETAILS\n")
    for emp in company:
        emp.showEmpDetails()
        
    dept = input("Enter Department for which you want to update salary")
    hike = eval(input("Enter hike in percentage : "))
    for emp in company:
        if emp.dept == dept:
            emp.updtSalary(hike)
            
    print("\nUPDATED EMPLOYEE DETAILS\n")
    for emp in company:
        emp.showEmpDetails()

main()

This Python program defines a simple Employee class with methods to manage employee details. Here’s a brief description:

  1. Employee Class:
    • The Employee class has attributes for the employee’s name, ID, department, and salary.
    • The __init__ method initializes these attributes.
    • The getEmpDetails method takes user input to set the employee details.
    • The showEmpDetails method prints the employee details.
    • The updtSalary method allows updating the employee’s salary.
  2. Example Instance:
    • The program creates an instance of the Employee class (e1).
    • It calls the getEmpDetails method to input employee details.
    • It calls the showEmpDetails method to display the entered details.
    • It calls the updtSalary method to update the employee’s salary.
  3. Output:
    • The program outputs the entered and updated employee details.

This program demonstrates the use of a class to model an employee, encapsulating related functionality and data. It also showcases how class methods can interact with instance variables and user input, providing a foundation for managing employee information in a more extensive human resources system.

Output

Enter Employee name :  Raju
Enter Employee ID :  SIT123
Enter Employee Dept :  CSE
Enter Employee Salary :  76500
Enter Employee name :  Jacob
Enter Employee ID :  SIT124
Enter Employee Dept :  ECE
Enter Employee Salary :  72000
Enter Employee name :  Seema
Enter Employee ID :  SIT125
Enter Employee Dept :  CSE
Enter Employee Salary :  75000
Enter Employee name :  Abdul
Enter Employee ID :  SIT126
Enter Employee Dept :  ME
Enter Employee Salary :  65000
Enter Employee name :  Babu
Enter Employee ID :  SIT127
Enter Employee Dept :  EEE
Enter Employee Salary :  64000

EMPLOYEE DETAILS

Employee Details
Name :  Raju
ID :  SIT123
Dept :  CSE
Salary :  76500
Employee Details
Name :  Jacob
ID :  SIT124
Dept :  ECE
Salary :  72000
Employee Details
Name :  Seema
ID :  SIT125
Dept :  CSE
Salary :  75000
Employee Details
Name :  Abdul
ID :  SIT126
Dept :  ME
Salary :  65000
Employee Details
Name :  Babu
ID :  SIT127
Dept :  EEE
Salary :  64000
Enter Department for which you want to update salary CSE
Enter hike in percentage :  10
Updated Salary for Raju
Updated Salary for Seema

UPDATED EMPLOYEE DETAILS

Employee Details
Name :  Raju
ID :  SIT123
Dept :  CSE
Salary :  84150.0
Employee Details
Name :  Jacob
ID :  SIT124
Dept :  ECE
Salary :  72000
Employee Details
Name :  Seema
ID :  SIT125
Dept :  CSE
Salary :  82500.0
Employee Details
Name :  Abdul
ID :  SIT126
Dept :  ME
Salary :  65000
Employee Details
Name :  Babu
ID :  SIT127
Dept :  EEE
Salary :  64000

Question 8

Polymorphism and Inheritance

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 Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar  9 12:20:20 2023

@author: Prabodh C P
"""

class PaliStr:
    def __init__(self):
        self.isPali = False
        
    def chkPalindrome(self, myStr):
        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):
        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")

This Python program defines two classes, PaliStr and PaliInt, which check whether a given string or integer is a palindrome. Here’s a brief description:

  1. PaliStr Class:
    • The PaliStr class has an attribute isPali initialized to False.
    • The __init__ method initializes the isPali attribute.
    • The chkPalindrome method checks whether a given string is a palindrome.
      • It compares the string with its reverse.
      • If they match, isPali is set to True, indicating a palindrome.
  2. PaliInt Class:
    • The PaliInt class is a subclass of PaliStr.
    • It has a similar structure but is designed to check palindromes for integers.
    • The chkPalindrome method reverses the digits of the integer and compares it with the original value.
  3. Example Usage:
    • The program takes user input for both a string and an integer.
    • It creates instances of PaliStr and PaliInt.
    • It calls the chkPalindrome method for each instance to check whether the given input is a palindrome.
    • The program then prints whether the string or integer is a palindrome based on the results.
  4. Output:
    • The program outputs whether the entered string and integer are palindromes.

This program demonstrates the use of class inheritance and polymorphism in Python. It provides a reusable and modular way to check whether a given input, whether a string or an integer, is a palindrome.

Output

Enter a string : madam
Given string is a Palindrome
Enter a integer : 567587
Given integer is not a Palindrome
Enter a string : INDIA
Given string is not a Palindrome
Enter a integer : 6789876
Given integer is a Palindrome

Question 9

Download XKCD comics

Write a python program to download the all XKCD comics

Python Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar  9 13:02:47 2023

@author: Prabodh C P
"""

import requests
import os
from bs4 import BeautifulSoup

# Set the URL of the first XKCD comic
url = 'https://xkcd.com/1/'

# Create a folder to store the comics
if not os.path.exists('xkcd_comics'):
    os.makedirs('xkcd_comics')

# Loop through all the comics
while True:
    try:
        # Download the page content
        res = requests.get(url)
        res.raise_for_status()

        # Parse the page content using BeautifulSoup
        soup = BeautifulSoup(res.text, 'html.parser')

        # Find the URL of the comic image
        comic_elem = soup.select('#comic img')
        if comic_elem == []:
            print('Could not find comic image.')
        else:
            comic_url = 'https:' + comic_elem[0].get('src')

            # Download the comic image
            print(f'Downloading {comic_url}...')
            res = requests.get(comic_url)
            res.raise_for_status()

            # Save the comic image to the xkcd_comics folder
            image_file = open(os.path.join('xkcd_comics', os.path.basename(comic_url)), 'wb')
            for chunk in res.iter_content(100000):
                image_file.write(chunk)
            image_file.close()

        # Get the URL of the previous comic
        prev_link = soup.select('a[rel="prev"]')[0]
        if not prev_link:
            break
        url = 'https://xkcd.com' + prev_link.get('href')

    except requests.exceptions.RequestException as e:
        print(f"Error: {e}")
        print("Stopping due to a bad URL.")
        break

print('All comics downloaded.')

This Python script downloads XKCD comics from the XKCD website and saves them to a local folder. Here’s a brief description:

  1. Initialization:
    • The script starts by setting the URL of the first XKCD comic (https://xkcd.com/1/).
    • It creates a folder named xkcd_comics to store the downloaded comics.
  2. Comic Download Loop:
    • The script enters a loop that iterates through XKCD comics.
    • For each iteration:
      • It sends an HTTP request to the specified URL using the requests library.
      • The HTML content of the page is parsed using BeautifulSoup to extract relevant information.
      • It finds the URL of the comic image on the page.
      • If the comic image is found, it downloads the image and saves it to the local xkcd_comics folder.
      • It then retrieves the URL of the previous comic to prepare for the next iteration.
  3. Output:
    • The script prints messages indicating the progress, such as downloading the comic image.
  4. Termination:
    • The loop continues until there are no more previous comics, indicating the end of the XKCD series.
    • The script prints ‘All comics downloaded’ when the process is complete.

This program automates the process of downloading XKCD comics, making it convenient for fans of the webcomic to archive the entire series locally. The use of the requests library simplifies web scraping, and the BeautifulSoup library aids in parsing HTML content. The program demonstrates web scraping techniques for extracting specific data from web pages.

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...
Downloading https://imgs.xkcd.com/comics/launch_window.png...
Downloading https://imgs.xkcd.com/comics/obituary_editor.png...
Downloading https://imgs.xkcd.com/comics/fanservice.png...
Downloading https://imgs.xkcd.com/comics/hand_dryers.png...

Spreadsheet Operations

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

Python Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar  9 15:34:37 2023

@author: Prabodh C P
"""

from openpyxl import Workbook 
from openpyxl.styles import Font

wb = Workbook() 
sheet = wb.active
sheet.title = "Language"
wb.create_sheet(title = "Capital")

lang = ["Kannada", "Telugu", "Tamil"]
state = ["Karnataka", "Telangana", "Tamil Nadu"]
capital = ["Bengaluru", "Hyderabad", "Chennai"]
code =['KA', 'TS', 'TN']

sheet.cell(row = 1, column = 1).value = "State"
sheet.cell(row = 1, column = 2).value = "Language"
sheet.cell(row = 1, column = 3).value = "Code"


ft = Font(bold=True)
for row in sheet["A1:C1"]:
    for cell in row:
        cell.font = ft
        
for i in range(2,5):
    sheet.cell(row = i, column = 1).value = state[i-2]
    sheet.cell(row = i, column = 2).value = lang[i-2]
    sheet.cell(row = i, column = 3).value = code[i-2]
    
wb.save("demo.xlsx")


sheet = wb["Capital"]

sheet.cell(row = 1, column = 1).value = "State"
sheet.cell(row = 1, column = 2).value = "Capital"
sheet.cell(row = 1, column = 3).value = "Code"

ft = Font(bold=True)
for row in sheet["A1:C1"]:
    for cell in row:
        cell.font = ft
        
for i in range(2,5):
    sheet.cell(row = i, column = 1).value = state[i-2]
    sheet.cell(row = i, column = 2).value = capital[i-2]
    sheet.cell(row = i, column = 3).value = code[i-2]
    
wb.save("demo.xlsx")
print("File demo.xlsx created successfully")

srchCode = input("Enter state code for finding capital ")
for i in range(2,5):
    data = sheet.cell(row = i, column = 3).value
    if data == srchCode:
        print("Corresponding capital for code", srchCode, "is", sheet.cell(row = i, column = 2).value)
        

sheet = wb["Language"]

srchCode = input("Enter state code for finding language ")
for i in range(2,5):
    data = sheet.cell(row = i, column = 3).value
    if data == srchCode:
        print("Corresponding language for code", srchCode, "is", sheet.cell(row = i, column = 2).value)

wb.close()

This Python script uses the openpyxl library to create an Excel workbook with two sheets, “Language” and “Capital”. It populates the sheets with data related to states, languages, capitals, and codes. The script then prompts the user to enter a state code and finds and prints the corresponding capital and language.

Here’s a brief description of the program:

  1. Workbook and Sheets Creation:
    • The script creates an Excel workbook using Workbook() from openpyxl.
    • It adds two sheets named “Language” and “Capital” using create_sheet().
  2. Data Population:
    • For each sheet, it populates the headers and data using nested loops and cell assignments.
    • Headers are formatted with bold using the Font class from openpyxl.styles.
  3. Saving the Workbook:
    • The workbook is saved with the name “demo.xlsx” using save().
  4. Search and Print:
    • The script prompts the user to enter a state code.
    • It then searches for the code in both sheets, “Language” and “Capital”.
    • If a match is found, it prints the corresponding capital or language.
  5. Workbook Closure:
    • The workbook is closed using close().

This program showcases the use of openpyxl for Excel file manipulation, including creating sheets, populating data, and searching for information within the workbook. It can be useful for managing data related to states, languages, and capitals in a structured Excel format.

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

Question 10

Merge selected pages from Multiple PDFs to a new PDF

Write a python program to combine select pages from many PDFs

Python Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar  9 17:34:55 2023

@author: Prabodh C P
"""

from PyPDF2 import PdfWriter, PdfReader

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

pdf1 = open('birds.pdf', 'rb')
pdf2 = open('birdspic.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)

This Python script uses the PyPDF2 library to combine specific pages from two PDF documents into a new PDF file. Here’s a brief description of the program:

  1. User Input:
    • The script prompts the user to enter a page number (num) that they want to combine from multiple documents.
  2. PDF File Opening:
    • It opens two existing PDF files, ‘birds.pdf’ and ‘birdspic.pdf’, in binary read mode ('rb').
  3. PDF Writer Initialization:
    • The script initializes a PdfWriter object from PyPDF2. This object will be used to write the combined pages to a new PDF file.
  4. Page Extraction and Combination:
    • It reads the specified page (num - 1 to adjust for zero-based indexing) from each input PDF using PdfReader from PyPDF2.
    • The extracted pages are added to the PdfWriter object.
  5. Output PDF Creation:
    • It writes the combined pages to a new PDF file named ‘output.pdf’ using the write() method.
  6. File Closure:
    • The input PDF files are closed using the close() method.

This program demonstrates a simple way to extract specific pages from different PDF documents and combine them into a new PDF file. It can be useful for scenarios where you want to create a new document by selecting specific pages from existing PDFs.

Output

This program allows you to extract specific pages from two PDF files, “birds.pdf” and “birdspic.pdf,” by entering the page numbers as user input. Once you input the desired page numbers, the program fetches those pages from both PDF files and combines them into a new file called “output.pdf.” This way, you can easily compile the desired pages from multiple PDF files into one document for your convenience.

Enter page number you want combine from multiple documents 3

Fetch weather data from the JSON

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

Python Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 10 09:22:53 2023

@author: Prabodh C P
"""

import json

# Load the JSON data from file
with open('weather_data.json') as f:
    data = json.load(f)

# Extract the required weather data
current_temp = data['main']['temp']
humidity = data['main']['humidity']
weather_desc = data['weather'][0]['description']

# Display the weather data
print(f"Current temperature: {current_temp}°C")
print(f"Humidity: {humidity}%")
print(f"Weather description: {weather_desc}")

JSON File :

{
  "coord": {
    "lon": -73.99,
    "lat": 40.73
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 15.45,
    "feels_like": 12.74,
    "temp_min": 14.44,
    "temp_max": 16.11,
    "pressure": 1017,
    "humidity": 64
  },
  "visibility": 10000,
  "wind": {
    "speed": 4.63,
    "deg": 180
  },
  "clouds": {
    "all": 1
  },
  "dt": 1617979985,
  "sys": {
    "type": 1,
    "id": 5141,
    "country": "US",
    "sunrise": 1617951158,
    "sunset": 1618000213
  },
  "timezone": -14400,
  "id": 5128581,
  "name": "New York",
  "cod": 200
}

This Python script reads weather data from a JSON file (‘weather_data.json’) and extracts specific information, such as current temperature, humidity, and weather description. Here’s a brief description of the program:

  1. JSON File Loading:
    • The script uses the json.load() function to load data from the ‘weather_data.json’ file, which presumably contains weather-related information in JSON format.
  2. Data Extraction:
    • It extracts key weather information from the loaded JSON data, such as current temperature (current_temp), humidity (humidity), and weather description (weather_desc).
  3. Displaying Weather Information:
    • The script prints the extracted weather data using formatted strings.
      • Current temperature is displayed in degrees Celsius.
      • Humidity is displayed as a percentage.
      • Weather description is displayed.
  4. Example JSON Structure:
    • The provided example JSON structure contains various weather-related details such as temperature, humidity, wind speed, and more. The script focuses on extracting specific data from this structure.

This program is useful for accessing and displaying relevant information from JSON files, which can be particularly handy for handling API responses or data stored in JSON format. In this example, it’s tailored for weather data retrieval.

Output

Current temperature: 15.45°C
Humidity: 64%
Weather description: clear sky

If you are also looking for the Algorithms Lab Manual ( 21CS42), Click on the link below

Design & Analysis of Algorithms Lab Manual – 21CS42

Prabodh C P is a faculty in the Dept of CSE SIT, Tumkur and also currently a Research Scholar pursuing PhD in IIT Hyderabad. He conducts online classes for C, C++, Python. For more info call +919392302100