PYTHON LAB MANUAL : Part II

Syllabus :

Python fundamentals, data types, operators, flow control and exception handling in Python, Creation of functions, passing parameters and return values. Manipulation of strings using string methods. Different collections like list, tuple and dictionary, Pattern recognition with and without using regular expressions, Reading, writing and organizing files. Concepts of classes, methods, objects and inheritance, Classes and methods with polymorphism and overriding, Working with excel spreadsheets and web scraping, Working with PDF, word and JSON files

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

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

Source Code :

mark1 = int (input("Enter the marks in the first test:"))
mark2 = int (input("Enter the marks in second test: "))
mark3 = int (input("Enter the marks in third test: "))

if (mark1 > mark2):
    if (mark2 > mark3):
        total_marks = mark1 + mark2
    else: 
        total_marks = mark1 + mark3
elif (mark1 > mark3):
    total_marks = mark1 + mark2
else:
    total_marks = mark2 + mark3
    
Average_marks = total_marks / 2
print ("The average of the best two test marks is:",Average_marks)

Output :

Enter the marks in the first test:18
Enter the marks in second test: 19
Enter the marks in third test: 24
The average of the best two test marks is: 21.5




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

Source Code :

num = int(input("Enter a number: "))
temp1 = num
reverse = 0
while temp1 > 0:
    remainder = temp1 % 10
    reverse = (reverse * 10) + remainder
    temp1 = temp1 // 10
if num == reverse:
  print('The Entered Number %d is Palindrome'%(num))
else:
  print("The Entered Number %d  is Not a Palindrome"%(num))

print("Digit\tFrequency")
for i in range(0,10):
    count=0
    temp2=num
    while temp2>0:
        digit=temp2%10
        if digit==i:
            count=count+1
        temp2=temp2//10
    if count>0:
        print(i,"\t",count)

Output:

Enter a number: 789923
The Entered Number 789923  is Not a Palindrome
Digit	Frequency
2 	 1
3 	 1
7 	 1
8 	 1
9 	 2

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

Source Code:

# Function for nth Fibonacci number
def Fibonacci(n):
    if n == 1:
        return 0
    elif n == 1 or n == 2:
        return 1
    else:
        return Fibonacci(n-1) + Fibonacci(n-2)

count = 1
N = int(input("Enter a value of N : "))
if N<=0:
    print("Invalid Input: Enter a value of N (>0)")
else:
    print("Fibonacci sequence : ")
    while count <= N:
       print(Fibonacci(count),end=' ')
       count = count + 1

Output:

Enter a value of N : 10
Fibonacci sequence : 
0 1 1 2 3 5 8 13 21 34 

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

Source code for binary to decimal: :

def bintodecima(b_num):
    value = 0
    for i in range(len(b_num)):
        digit = b_num.pop()
        if digit == '1':
            value = value + pow(2, i)
    return value
b_num = list(input("Input a binary number: "))
value = bintodecima(b_num)
print("The decimal value of the number is", value)

Output:

Input a binary number: 100
The decimal value of the number is 4

Source code for octal to hexadecimal:

# Octal to Hexadecimal using List and while Loop
print("Enter the Octal Number: ")
octnum = int(input())

chk = 0
i = 0
decnum = 0
while octnum!=0:
    rem = octnum%10
    if rem>7:
        chk = 1
        break
    decnum = decnum + (rem * (8 ** i))
    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
        else:
            rem = rem + 55
        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!")

Output :

Enter the Octal Number: 
7302

Equivalent Hexadecimal Value is: 
EC2

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

Source Code:

sentence = input("Enter a sentence: ")
(words, digits, upper, lower) = (0, 0, 0, 0)
l_w = sentence.split()
words =  len(l_w)
for ch in sentence:
    if ch.isdigit():
        digits = digits + 1
    elif ch.isupper():
        upper = upper + 1
    elif ch.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: I am Palguni GT and My usn is 12345_MCE
No of Words:  9
No of Digits:  5
No of Uppercase letters:  8
No of Lowercase letters:  17

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

Sample Output:
Original string:
Python Exercises
Python Exercises
Similarity between two said strings:
1.0
Sample Output:
Original string:
Python Exercises
Python Exercise
Similarity between two said strings:
0.967741935483871

Source Code:

def similarity(str1, str2):
    len1 = len(str1)
    len2 = len(str2)
    max_len = max(len1, len2)

    common_chars = 0
    for i in range(max_len):
        if i < len1 and i < len2 and str1[i] == str2[i]:
            common_chars += 1

    return common_chars / max_len

str1 = input("Enter the first string: ")
str2 = input("Enter the second string: ")

print("Original string1:\n", str1)
print("Second string:\n",str2)

print("Similarity between two said strings:")
print(similarity(str1, str2))

Output1:

Enter the first string: Python Exercises
Enter the second string: Python Exercises
Original string1:
 Python Exercises
Second string:
 Python Exercises
Similarity between two said strings:
1.0

Output2:

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

Source Code of Insertion Sort:

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

arr = input("Enter a list of numbers separated by commas: ").split(",")
arr = [int(x) for x in arr]

print("Original list:", arr)

insertion_sort(arr)

print("Sorted list:", arr)

Output:

Enter a list of numbers separated by commas: 12,11,13,5,6
Original list: [12, 11, 13, 5, 6]
Sorted list: [5, 6, 11, 12, 13]

Source Code of Merge Sort:

def merge_sort(arr):
    if len(arr) > 1:
        mid = len(arr) // 2
        left = arr[:mid]
        right = arr[mid:]

        merge_sort(left)
        merge_sort(right)

        i = j = k = 0

        while i < len(left) and j < len(right):
            if left[i] < right[j]:
                arr[k] = left[i]
                i += 1
            else:
                arr[k] = right[j]
                j += 1
            k += 1

        while i < len(left):
            arr[k] = left[i]
            i += 1
            k += 1

        while j < len(right):
            arr[k] = right[j]
            j += 1
            k += 1

arr = input("Enter a list of numbers separated by commas: ").split(",")
arr = [int(x) for x in arr]

print("Original list:", arr)

merge_sort(arr)

print("Sorted list:", arr)

Output:

Enter a list of numbers separated by commas: 12,11,13,5,6
Original list: [12, 11, 13, 5, 6]
Sorted list: [5, 6, 11, 12, 13]

8. Write a program to convert roman numbers in to integer values using dictionaries.

Source Code:

def roman_to_int(s):
    roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    res = 0
    prev = 0
    for i in range(len(s)-1, -1, -1):
        curr = roman_dict[s[i]]
        if curr < prev:
            res -= curr
        else:
            res += curr
        prev = curr
    return res

s = input("Enter a Roman numeral: ")
print("The integer value of", s, "is:", roman_to_int(s))

Output:

Enter a Roman numeral: XVI
The integer value of XVI is: 16

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

Source Code without using regular expression:

def isphonenumber(number):
    if len(number) != 12:
        return False
    for i in range(0, 3):
        if not number[i].isdecimal():
            return False
    if number[3] != '-':
        return False
    for i in range(4, 7):
        if not number[i].isdecimal():
            return False
    if number[7] != '-':
        return False
    for i in range(8, 12):
        if not number[i].isdecimal():
            return False
    return True

# Test the isphonenumber() function without using regular expressions
print(isphonenumber('415-555-4242'))  # True
print(isphonenumber('415-555-424'))   # False
print(isphonenumber('415-555-42422')) # False
print(isphonenumber('415-555-4a42'))  # False

Output:

True
False
False
False

Source Code using regular expression:

import re
def isphonenumber_regex(number):
    pattern = re.compile(r'\d{3}-\d{3}-\d{4}')
    return bool(pattern.match(number))

print(isphonenumber_regex('415-555-4242'))  # True
print(isphonenumber_regex('415-555-424'))   # False
print(isphonenumber_regex('415-555-42422')) # False
print(isphonenumber_regex('415-555-4a42'))  # False

Output:

True
False
False
False

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

Source Code:

import re

def find_phone_numbers_and_emails(filename):
    # Read the contents of the file
    with open(filename, 'r') as file:
        text = file.read()

    # Find all phone numbers in the text
    phone_numbers = re.findall(r'\+\d{11}', text)

    # Find all email addresses in the text
    email_addresses = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)

    # Return the results
    return phone_numbers, email_addresses

# Test the function with a sample text file
filename = 'sample.txt'
phone_numbers, email_addresses = find_phone_numbers_and_emails(filename)

# Print the results
print('Phone numbers:')
for number in phone_numbers:
    print(number)

print('\nEmail addresses:')
for email in email_addresses:
    print(email)

Output:

Phone numbers:
+91948012352

Email addresses:
tocxten@gmail.com

11. 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 and 2.Find the frequency of occurrence of the word accepted from the user in the file

Source Code:

# Prompt the user for a file name
file_name = input("Enter the file name: ")

# Prompt the user for the number of lines to display
n = int(input("Enter the number of lines to display: "))

# Prompt the user for the word to search for
word = input("Enter a word to search for: ")

# Open the file and read the first N lines
with open(file_name, "r") as f:
    for i in range(n):
        line = f.readline()
        print(line.strip())

# Count the frequency of the word in the file
with open(file_name, "r") as f:
    content = f.read()
    count = content.count(word)

# Display the frequency of the word
print(f"The word '{word}' appears {count} times in the file.")

Output:

12.Write a python program to create a ZIP file of a particular folder which contains several files inside it.

Source Code:

import zipfile
import os

def create_zip_folder(folder_path, zip_file_path):
    # Create a ZipFile object
    with zipfile.ZipFile(zip_file_path, 'w', zipfile.ZIP_DEFLATED) as zip_file:
        # Walk through the folder and add each file to the ZIP file
        for root, dirs, files in os.walk(folder_path):
            for file in files:
                file_path = os.path.join(root, file)
                zip_file.write(file_path, file)

    print(f'{zip_file_path} created successfully!')

# Example usage
create_zip_folder('path/to/folder', 'folder.zip')

Output:

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

Source Code:

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, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

# Example usage
t = Triangle(4, 6)
print(f"The area of the triangle is {t.area()}")

c = Circle(5)
print(f"The area of the circle is {c.area()}")

r = Rectangle(3, 7)
print(f"The area of the rectangle is {r.area()}")

Output:

The area of the triangle is 12.0
The area of the circle is 78.53981633974483
The area of the rectangle is 21

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

Source Code:


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, new_salary):
        if self.department == department:
            self.salary = new_salary

# Create a list of employees
employees = [
    Employee('Alice', 'E123', 'Sales', 50000),
    Employee('Bob', 'E456', 'IT', 60000),
    Employee('Charlie', 'E789', 'Sales', 55000),
    Employee('David', 'E012', 'IT', 65000)
]

# Print the initial existing salaries
print("The existing Salaries : ")
for employee in employees:
    print(f'{employee.name} ({employee.department}): ${employee.salary:,}')
print("\n")
# Prompt the user to enter the department and new salary
department = input('Enter the department: ')
new_salary = int(input('Enter the new salary: '))

# Update the salaries of employees in the specified department
for employee in employees:
    employee.update_salary_by_department(department, new_salary)
    
# Print the updated salaries
print("The updated Salaries : ")
for employee in employees:
    print(f'{employee.name} ({employee.department}): ${employee.salary:,}')

Output:

The existing Salaries : 
Alice (Sales): $50,000
Bob (IT): $60,000
Charlie (Sales): $55,000
David (IT): $65,000


Enter the department: Sales
Enter the new salary: 25000
The updated Salaries : 
Alice (Sales): $25,000
Bob (IT): $60,000
Charlie (Sales): $25,000
David (IT): $65,000

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

Source Code:

class Palindrome:
    def is_palindrome(self, input):
        pass

class StringPalindrome(Palindrome):
    def is_palindrome(self, input):
        return input == input[::-1]

class IntegerPalindrome(Palindrome):
    def is_palindrome(self, input):
        return str(input) == str(input)[::-1]

# Example usage
sp = StringPalindrome()
print(sp.is_palindrome("racecar"))   # True
print(sp.is_palindrome("hello"))     # False

ip = IntegerPalindrome()
print(ip.is_palindrome(12321))       # True
print(ip.is_palindrome(12345))       # False

Output:

True
False
True
False

In this program, we define a base class called Palindrome with a method called is_palindrome. We then define two derived classes: StringPalindrome and IntegerPalindrome, each with their own implementations of the is_palindrome method.

The StringPalindrome class checks whether the input string is equal to its reverse using slicing.

The IntegerPalindrome class converts the input integer to a string and checks whether it is equal to its reverse.

Finally, we create instances of each class and call their is_palindrome method with a string and an integer to check whether they are palindromes.

Note that in this program, we use the pass statement in the base class’s is_palindrome method to indicate that it should be overridden in the derived classes. We also use polymorphism to call the appropriate is_palindrome method based on the type of the input.

16. Write a python program to download the all XKCD comics

Source Code: Here’s an example Python program using the requests and os libraries to download all XKCD comics:

import requests
import os

# Create a directory to store the comics
os.makedirs('xkcd', exist_ok=True)

# Start from the latest comic and work backwards
url = 'https://xkcd.com/info.0.json'
response = requests.get(url)
response.raise_for_status()
latest_comic = response.json()['num']
for comic_num in range(latest_comic, 0, -1):
    # Get the JSON data for the current comic
    url = f'https://xkcd.com/{comic_num}/info.0.json'
    response = requests.get(url)
    response.raise_for_status()
    comic_data = response.json()

    # Download the image for the current comic
    image_url = comic_data['img']
    response = requests.get(image_url)
    response.raise_for_status()

    # Save the image to a file
    file_name = os.path.basename(image_url)
    with open(f'xkcd/{file_name}', 'wb') as image_file:
        for chunk in response.iter_content(100000):
            image_file.write(chunk)

    # Print a message for the user
    print(f'Downloaded {file_name}')

In this example, we start by using the os library to create a new directory named xkcd to store the comics. The exist_ok=True parameter ensures that the program won’t raise an error if the directory already exists.

We then use the requests library to get the JSON data for the latest XKCD comic from the URL https://xkcd.com/info.0.json. We use the raise_for_status method to raise an exception if there was an error getting the data. We then extract the num attribute from the JSON data to get the number of the latest comic.

Next, we loop through all the comic numbers from the latest comic down to 1 using a for loop with a step of -1. For each comic number, we get the JSON data for the comic from the URL https://xkcd.com/{comic_num}/info.0.json using the requests library. We extract the image URL from the JSON data and download the image using the requests library again. We use the basename function from the os.path module to extract the file name from the image URL and save the image to a file in the xkcd directory using the open function with the 'wb' mode to write the image as a binary file. We use the iter_content method of the Response object to download the image in chunks and write each chunk to the file.

Finally, we print a message for the user indicating which comic was downloaded. The resulting images will be saved in the xkcd directory in the same directory as the Python script.

info.0.json: info.0.json is a JSON file that contains metadata about the latest XKCD comic. Here’s an example of the contents of the file:

{
   "month": "4",
   "num": 2553,
   "link": "",
   "year": "2022",
   "news": "",
   "safe_title": "Interview",
   "transcript": "",
   "alt": "It's tough to get excited about a new job when you're already doing the same thing but for a different company.",
   "img": "https://imgs.xkcd.com/comics/interview.png",
   "title": "Interview",
   "day": "25"
}

Output:

Downloaded recipe_relativity.png
Downloaded helium_reserve.png
Downloaded escape_speed.png
Downloaded cosmological_nostalgia_content.png
Downloaded linguistics_gossip.png
Downloaded diffraction_spikes.png
Downloaded 1_to_1_scale.png
Downloaded paleontology_museum.png
Downloaded easily_confused_acronyms.png
Downloaded my_favorite_things.png
Downloaded towed_message.png
Downloaded qualifications.png
..............................

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

here’s an example Python program using the openpyxl library to read data from a spreadsheet and write data to a new spreadsheet:

Source Code:

import openpyxl

# Open the input spreadsheet
input_workbook = openpyxl.load_workbook('input.xlsx')

# Select the first sheet
input_sheet = input_workbook.active

# Create a new workbook and select the first sheet
output_workbook = openpyxl.Workbook()
output_sheet = output_workbook.active

# Loop through the rows in the input sheet and copy the data to the output sheet
for row_num in range(1, input_sheet.max_row + 1):
    # Create a list to store the values for the current row
    row_values = []
    for col_num in range(1, input_sheet.max_column + 1):
        # Get the value from the current cell in the input sheet
        cell_value = input_sheet.cell(row=row_num, column=col_num).value
        # Add the value to the list of row values
        row_values.append(cell_value)
    # Add the row values to the output sheet
    output_sheet.append(row_values)

# Save the output workbook
output_workbook.save('output.xlsx')

In this example, we start by using the openpyxl library to load the input spreadsheet file, input.xlsx, into an input_workbook object. We then select the first sheet in the workbook using the active attribute.

Next, we create a new workbook using the openpyxl.Workbook() constructor and select the first sheet using the active attribute. This new workbook will be used to store the output data.

We then loop through each row in the input sheet using the max_row attribute of the Worksheet object. For each row, we create a list to store the values for that row. We then loop through each column in the row using the max_column attribute of the Worksheet object. For each column, we get the value from the corresponding cell in the input sheet using the cell method of the Worksheet object and add it to the list of row values.

Once we have all the row values, we add them to the output sheet using the append method of the Worksheet object.

Finally, we save the output workbook to a new file, output.xlsx, using the save method of the Workbook object. The resulting file will be saved in the same directory as the Python script.

Output:

18. Write a python program to combine select pages from many PDFs

To combine select pages from many PDFs using Python, you can use the PyPDF2 library. Here’s an example program that reads in several PDFs and combines specific pages from each into a new PDF:

Source Code:

import PyPDF2

# List of input PDF files and their corresponding page numbers
pdf_files = [
    {'file': 'document1.pdf', 'pages': [1, 3]},
    {'file': 'document2.pdf', 'pages': [2]},
    {'file': 'document3.pdf', 'pages': [1, 2, 3]}
]

# Create a new PDF file to write to
output_pdf = PyPDF2.PdfWriter()

# Loop through each input file and add the selected pages to the output PDF
for file in pdf_files:
    with open(file['file'], 'rb') as input_pdf:
        input_pdf_reader = PyPDF2.PdfReader(input_pdf)
        for page_num in file['pages']:
            page = input_pdf_reader.pages[page_num-1]
            output_pdf.add_page(page)

# Write the output PDF to a file
with open('combined_pages.pdf', 'wb') as output_file:
    output_pdf.write(output_file)

Output:

In this example, we start by defining a list of dictionaries that contains the filenames of the input PDF files and a list of the page numbers that we want to include from each file. We then create a new PdfFileWriter object to store the selected pages.

Next, we loop through each input PDF file in the list and open it using the open function with the 'rb' mode to read it as a binary file. We then use the PdfFileReader object to read in the pages of the PDF file.

For each file, we loop through the selected page numbers and add each page to the output PDF using the addPage method of the PdfFileWriter object. Note that the page numbers in the list are 1-based, so we subtract 1 from each page number to get the correct 0-based index for the getPage method.

Finally, we write the output PDF to a file using the write method of the PdfFileWriter object and the open function with the 'wb' mode to write it as a binary file. The resulting file will be named combined_pages.pdf in the same directory as the Python script.

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

Sample JSON File: Here’s an example program that reads weather data from a JSON file and prints out the current temperature:

{
  "coord": {
    "lon": -122.08,
    "lat": 37.39
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 22.0,
    "feels_like": 22.0,
    "temp_min": 20.0,
    "temp_max": 24.0,
    "pressure": 1018,
    "humidity": 50
  },
  "visibility": 10000,
  "wind": {
    "speed": 4.6,
    "deg": 330
  },
  "clouds": {
    "all": 1
  },
  "dt": 1619021689,
  "sys": {
    "type": 1,
    "id": 5122,
    "country": "US",
    "sunrise": 1619008936,
    "sunset": 1619056278
  },
  "timezone": -25200,
  "id": 420006353,
  "name": "San Francisco",
  "cod": 200
}

This JSON file contains weather data for the city of San Francisco. The structure of the file is similar to the JSON data returned by the OpenWeatherMap API. It includes information such as the coordinates of the city, the current weather conditions, temperature, humidity, wind speed, and more.

Source Code:

import json

# Open the JSON file
with open('weather_data.json', 'r') as file:
    # Load the JSON data into a dictionary
    data = json.load(file)

# Extract the current temperature from the dictionary
current_temp = data['main']['temp']

# Print the current temperature
print(f"The current temperature is {current_temp} degrees Celsius.")

Output:

The current temperature is 22.0 degrees Celsius.

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.

Project Assignment 1: Based on the Concepts of Lists, tuples, sets, and dictionaries.

Project Title: Data Analysis of Student Grades

Project Description: In this project, you will use Python’s built-in data structures – lists, tuples, sets, and dictionaries – to analyze and process a set of student grades. You will perform calculations on the data, store it in appropriate data structures, and output the results in a readable format.

Tasks:

  1. Create a list of student names.
  2. Create a dictionary of student grades, where each key is a student name and the value is a list of grades.
  3. Calculate the average grade for each student and store it in a new dictionary, where each key is a student name and the value is the average grade.
  4. Create a set of all unique grades.
  5. Calculate the class average grade.
  6. Output the results in a readable format, including the student name, grades, and average grade, as well as the unique grades and class average.

Sample Output:

Student Name: John Doe
Grades: [90, 85, 95, 80]
Average Grade: 87.5

Student Name: Jane Smith
Grades: [92, 95, 90, 89]
Average Grade: 91.5
Unique Grades: {80, 85, 89, 90, 92, 95}
Class Average: 89.5

Project Assignment 2: Based on the Concepts of Regular Expressions

Project Title: Email Address Validation using Regular Expressions

Project Description: In this project, you will use Python’s regular expressions module to validate email addresses. You will write a Python program that reads a set of email addresses from a text file and determines if each email address is valid or not. You will use regular expressions to validate the email addresses based on the following criteria:

  1. The email address must have a valid format, including an “@” symbol and a top-level domain (e.g., “.com”, “.org”, “.edu”).
  2. The email address must not contain any invalid characters, such as spaces, commas, or semicolons.
  3. The email address must not be too long (e.g., more than 255 characters).

Tasks:

  1. Read a set of email addresses from a text file.
  2. Create a regular expression that matches valid email addresses based on the criteria listed above.
  3. Loop through each email address and apply the regular expression to determine if it is valid or not.
  4. Store the valid email addresses in a list.
  5. Output the list of valid email addresses.

Sample Input (emails.txt):

johndoe@example.com
jane.smith@example.org
invalid.email
another.invalid.email@example.com
toolongemailaddress1234567890123456789012345678901234567890123456789012345678901234567890@example.com

Sample Output:

johndoe@example.com
jane.smith@example.org
another.invalid.email@example.com

Project Assignment 3: Based on the concepts of Classes and Objects

You are asked to create a program for a library management system that tracks information about books, authors, and borrowers. The system should be able to perform the following tasks:

  1. Add new books to the library with their title, author, ISBN, and number of copies available.
  2. Allow borrowers to check out books, reducing the number of available copies.
  3. Allow borrowers to return books, increasing the number of available copies.
  4. Display a list of all books in the library, along with their current availability.
  5. Display a list of all borrowers and the books they have checked out.

To implement this system, you should create the following classes:

  1. A Book class with attributes for the book’s title, author, ISBN, and number of copies available.
  2. An Author class with attributes for the author’s name and a list of their books.
  3. A Borrower class with attributes for the borrower’s name and a list of the books they have checked out.
  4. A Library class that contains lists of books, authors, and borrowers, as well as methods for adding books, checking out and returning books, and displaying book and borrower information.

Your program should allow the user to interact with the library system via a command-line interface. They should be able to add new books, check out and return books, and view information about books and borrowers.

To complete the project, you should implement all of the necessary classes and methods, as well as a command-line interface that allows the user to interact with the system. You should also test your program thoroughly to ensure that it works correctly in all cases.

Project Assignment 4: based on the concepts of File Handling

You are tasked with creating a program that can read and process data from a CSV file containing information about customers and their orders. The CSV file contains columns for customer name, order date, order total, and a list of items ordered. Your program should be able to perform the following tasks:

  1. Read the data from the CSV file and store it in a suitable data structure.
  2. Calculate the total revenue generated by the orders in the file.
  3. Calculate the average order total for each customer.
  4. Identify the customer who has spent the most money, and display their name and total spent.
  5. Identify the most popular item ordered, and display the item name and number of times ordered.
  6. Allow the user to search for orders by customer name or date.

To implement this system, you should create the following classes:

  1. A Customer class with attributes for the customer’s name and a list of their orders.
  2. An Order class with attributes for the order date, order total, and a list of items ordered.
  3. An Item class with attributes for the item name and price.

Your program should allow the user to interact with the system via a command-line interface. They should be able to view revenue and order statistics, search for orders, and view details about individual customers and orders.

To complete the project, you should implement all of the necessary classes and methods, as well as a function for reading data from the CSV file and storing it in the appropriate data structure. You should also test your program thoroughly to ensure that it works correctly in all cases.

Project Assignment 5: based on the concepts of Web scraping.

You are tasked with creating a program that can scrape data from a website and perform analysis on the results. The website you will be scraping is an online bookstore that contains information about books and their authors. Your program should be able to perform the following tasks:

  1. Scrape the website to collect data on all books and their authors.
  2. Allow the user to search for books by title, author, or genre.
  3. Calculate the average rating and number of ratings for each book.
  4. Identify the most popular authors and genres based on the number of books and ratings.
  5. Generate a report that summarizes the data collected and presents it in a clear and concise format.

To implement this system, you should use a web scraping library like Beautiful Soup or Scrapy to extract data from the website. You should also create classes for books and authors, and use these classes to organize the data and perform calculations.

Your program should allow the user to interact with the system via a command-line interface. They should be able to search for books, view statistics on ratings and popularity, and generate a report on the data collected.

To complete the project, you should implement all of the necessary classes and methods, as well as a function for scraping data from the website and storing it in the appropriate data structure. You should also test your program thoroughly to ensure that it works correctly in all cases.

Project Assignment 6: Based on the concepts of Functions.

In this project assignment, you will be required to create a Python program that includes multiple functions for various tasks. You will need to write the code for each function and also provide comments to explain what each function does.

Task 1: String Reversal

Write a function called ‘reverse_string’ that accepts a string as input and returns the reversed version of the string. For example, if the input string is “hello”, the output should be “olleh”.

Task 2: List Sorting

Write a function called ‘sort_list’ that accepts a list of integers as input and returns the sorted version of the list in ascending order.

Task 3: Average Calculation

Write a function called ‘calculate_average’ that accepts a list of integers as input and returns the average of the integers in the list.

Task 4: Prime Number Check

Write a function called ‘is_prime’ that accepts an integer as input and returns True if the input is a prime number, otherwise it should return False.

Task 5: Palindrome Check

Write a function called ‘is_palindrome’ that accepts a string as input and returns True if the string is a palindrome, otherwise it should return False. A palindrome is a word or phrase that reads the same backwards as forwards.

Task 6: User Input and Function Calling

In your main program, prompt the user to enter a string, a list of integers and an integer. Then call each of the functions you have defined above using the user inputs as the parameters. Print out the results of each function call.

Viva Questions

1. Viva questions on Python fundamentals, data types, operators, flow control, and exception handling in Python:

  1. What is Python, and what are some of its key features?
  2. What are the different data types in Python?
  3. What are variables in Python, and how are they declared?
  4. What is the difference between single and double quotes in Python?
  5. How can you convert a string to an integer or float in Python?
  6. What is the difference between a list and a tuple in Python?
  7. How do you access elements in a list or a tuple?
  8. What is a dictionary in Python, and how is it used?
  9. What is an operator in Python?
  10. What is the difference between arithmetic and logical operators?
  11. What is a conditional statement in Python, and how is it used?
  12. What are loops in Python, and how are they used?
  13. What is the difference between a for loop and a while loop in Python?
  14. How do you break out of a loop in Python?
  15. What is a function in Python, and how is it defined?
  16. What is the purpose of the return statement in Python?
  17. What are default arguments in Python?
  18. How are exceptions handled in Python?
  19. What is the purpose of the try-except block in Python?
  20. What is the difference between the except and finally clauses in a try-except block?
  21. How do you raise an exception in Python?
  22. What is the purpose of the else clause in a try-except block?
  23. How do you handle multiple exceptions in a single try-except block?
  24. What is the purpose of the assert statement in Python?
  25. What are some common built-in exceptions in Python, and when do they occur?

2.Viva Questions on “ creation of functions, passing parameters and return values “

  1. What is a function in Python?
  2. How do you define a function in Python?
  3. What is the syntax for defining a function with parameters?
  4. How do you call a function in Python?
  5. What is the purpose of parameters in a function?
  6. How do you pass arguments to a function in Python?
  7. What is the difference between positional and keyword arguments?
  8. Can you have a function without parameters in Python?
  9. How do you return a value from a function in Python?
  10. What is the difference between the print() function and the return statement?
  11. Can a function return multiple values in Python?
  12. How do you assign the return value of a function to a variable?
  13. Can a function have both input parameters and return values?
  14. What happens if a function does not have a return statement?
  15. Can you change the value of a variable inside a function?
  16. What is the purpose of the global keyword in Python?
  17. How do you pass a variable by reference in Python?
  18. Can you have a function that takes a variable number of arguments?
  19. What is a default argument, and how is it used in function parameters?
  20. How do you define a function with a variable number of keyword arguments?
  21. What is a lambda function in Python?
  22. How do you use the map() function with a lambda function?
  23. What is the difference between a function definition and a function call?
  24. Can you nest functions inside other functions in Python?
  25. How do you document a function in Python using docstrings?

3.Viva Questions on ” manipulation of strings using string methods “

  1. What are strings in Python?
  2. How do you define a string in Python?
  3. What are string methods?
  4. How do you find the length of a string using a string method?
  5. How do you convert a string to uppercase using a string method?
  6. How do you convert a string to lowercase using a string method?
  7. What is string concatenation, and how is it performed in Python?
  8. How do you check if a specific substring exists in a string using a string method?
  9. How do you replace a substring with another substring using a string method?
  10. How do you split a string into a list of substrings using a string method?
  11. How do you join a list of strings into a single string using a string method?
  12. How do you remove whitespace from the beginning and end of a string using a string method?
  13. How do you count the occurrences of a specific character in a string using a string method?
  14. How do you find the index of a specific character in a string using a string method?
  15. How do you check if a string starts or ends with a specific substring using a string method?
  16. How do you check if a string is composed of only alphanumeric characters using a string method?
  17. How do you check if a string is numeric using a string method?
  18. How do you convert a string to a list of characters using a string method?
  19. How do you reverse the order of characters in a string using a string method?
  20. How do you check if all characters in a string are in uppercase or lowercase using a string method?
  21. How do you extract a substring from a string using a string method?
  22. How do you check if a string is a valid identifier using a string method?
  23. How do you capitalize the first character of a string using a string method?
  24. How do you check if a string is empty using a string method?
  25. How do you check if a string contains only whitespace characters using a string method?

4. Viva Questions on ” list, tuple and dictionary “

  1. What are lists in Python?
  2. How do you define a list in Python?
  3. How do you access elements in a list?
  4. Can a list contain elements of different data types?
  5. How do you add an element to a list?
  6. How do you remove an element from a list?
  7. What is the difference between append() and extend() methods in lists?
  8. How do you find the length of a list?
  9. How do you check if an element exists in a list?
  10. How do you sort a list in ascending order?
  11. How do you reverse the order of elements in a list?
  12. What are tuples in Python?
  13. How do you define a tuple in Python?
  14. How do you access elements in a tuple?
  15. Can you modify elements in a tuple?
  16. What is the difference between a list and a tuple?
  17. What is a dictionary in Python?
  18. How do you define a dictionary in Python?
  19. How do you access values in a dictionary?
  20. How do you add a key-value pair to a dictionary?
  21. How do you remove a key-value pair from a dictionary?
  22. How do you check if a key exists in a dictionary?
  23. How do you find the length of a dictionary?
  24. How do you retrieve all the keys or values from a dictionary?
  25. How do you loop through a dictionary in Python?

5. Viva Questions on ”   pattern recognition with and without using regular expressions “

  1. What is pattern recognition in the context of programming?
  2. What are regular expressions (regex)?
  3. How do you define a regular expression in Python?
  4. How do you search for a pattern in a string using regular expressions?
  5. What is the difference between searching and matching in regular expressions?
  6. How do you extract specific portions of a string using regular expressions?
  7. How do you replace a pattern in a string using regular expressions?
  8. How do you check if a string matches a specific pattern using regular expressions?
  9. What are some commonly used metacharacters in regular expressions?
  10. How do you use character classes in regular expressions?
  11. How do you specify the number of occurrences of a pattern using quantifiers in regular expressions?
  12. How do you use anchors in regular expressions to match the start or end of a string?
  13. How do you use groups and capturing in regular expressions?
  14. How do you use the pipe symbol (|) for alternative matching in regular expressions?
  15. How do you use the dot (.) metacharacter in regular expressions to match any character?
  16. What are some special sequences in regular expressions, and how do you use them?
  17. How do you enable case-insensitive matching in regular expressions?
  18. How do you use lookaheads and lookbehinds in regular expressions?
  19. What are some limitations of regular expressions?
  20. Can you perform pattern recognition without regular expressions in Python?
  21. How do you implement pattern recognition using string methods in Python?
  22. What string methods are commonly used for pattern recognition in Python?
  23. What are some advantages of using regular expressions for pattern recognition?
  24. How do you handle complex patterns and nested matches in regular expressions?
  25. How do you validate user input using regular expressions in Python?

6. Viva Questions on ” reading, writing and organizing files.  “

  1. How do you open a file in Python?
  2. What are the different modes used in file opening?
  3. How do you read the contents of a file in Python?
  4. How do you write data to a file in Python?
  5. What is the difference between the “w” and “a” modes for file writing?
  6. How do you close a file after reading or writing?
  7. How do you check if a file exists before opening it?
  8. How do you handle errors when opening or working with files?
  9. How do you read a specific number of characters from a file?
  10. How do you read lines from a file and store them in a list?
  11. How do you write multiple lines to a file at once?
  12. How do you append data to an existing file in Python?
  13. How do you create a new directory in Python?
  14. How do you check if a directory exists in Python?
  15. How do you delete a file in Python?
  16. How do you rename a file or directory in Python?
  17. How do you navigate through directories and subdirectories in Python?
  18. How do you recursively list all files in a directory and its subdirectories?
  19. How do you copy a file from one location to another in Python?
  20. How do you get the size of a file in Python?
  21. How do you read and write binary files in Python?
  22. How do you read and write CSV files in Python?
  23. How do you read and write JSON files in Python?
  24. How do you read and write XML files in Python?
  25. How do you handle encoding and decoding issues when working with files in Python?

7. Viva Questions on ” Concepts of classes, methods, objects and inheritance “

  1. What is object-oriented programming (OOP)?
  2. What is a class in Python?
  3. How do you define a class in Python?
  4. What are attributes and methods in a class?
  5. How do you create an object from a class in Python?
  6. How do you access attributes and call methods of an object?
  7. What is the difference between a class and an object?
  8. How do you define attributes in a class?
  9. How do you define methods in a class?
  10. What is the self keyword in Python?
  11. How do you initialize the attributes of an object?
  12. What is the init method in Python classes used for?
  13. How do you define a method with parameters in a class?
  14. What is method overloading in Python?
  15. How do you define a static method in a class?
  16. What is inheritance in Python?
  17. How do you create a subclass from a parent class?
  18. What is the difference between single inheritance and multiple inheritance?
  19. How do you override methods in a subclass?
  20. How do you access methods and attributes of a parent class from a subclass?
  21. What is method overriding in Python?
  22. What is the super() function used for in inheritance?
  23. How do you check if a class is a subclass of another class?
  24. What are abstract classes and abstract methods in Python?
  25. How do you implement encapsulation, inheritance, and polymorphism in Python classes?

8. Viva Questions on ” classes and methods with polymorphism and overriding  “

  1. What is polymorphism in object-oriented programming?
  2. How is polymorphism achieved in Python?
  3. What is method overriding in Python?
  4. How do you override a method in a subclass?
  5. What is the purpose of the super() function in method overriding?
  6. How do you call the overridden method from the subclass?
  7. What happens if a method is not overridden in a subclass?
  8. How do you implement polymorphism using inheritance in Python?
  9. What is dynamic polymorphism in Python?
  10. How do you define an abstract class in Python?
  11. What is the purpose of abstract methods in Python?
  12. Can you instantiate an object of an abstract class in Python?
  13. How do you implement polymorphism using abstract classes and methods in Python?
  14. What is method overloading in Python?
  15. Can you have method overloading in Python?
  16. How do you achieve method overloading in Python?
  17. What is the difference between method overriding and method overloading?
  18. Can you override a static method in Python?
  19. How do you handle exceptions in overridden methods?
  20. Can you have private methods in Python classes?
  21. What is the purpose of name mangling in Python?
  22. How do you access private methods and attributes in Python?
  23. How do you implement method overloading with different data types in Python?
  24. Can you override built-in methods in Python classes?
  25. How do you implement polymorphism without using inheritance in Python?

9. Viva Questions on “working with excel spreadsheets and web scraping   “

  1. How do you read data from an Excel spreadsheet in Python?
  2. What libraries are commonly used for working with Excel files in Python?
  3. How do you install the required libraries for working with Excel in Python?
  4. How do you write data to an Excel spreadsheet in Python?
  5. How do you create a new Excel spreadsheet using Python?
  6. How do you open an existing Excel spreadsheet and modify its contents in Python?
  7. How do you read a specific sheet from an Excel file in Python?
  8. How do you write data to a specific sheet in an Excel file using Python?
  9. How do you add formatting, such as bold or color, to cells in an Excel spreadsheet using Python?
  10. How do you apply formulas to cells in an Excel spreadsheet using Python?
  11. How do you merge cells in an Excel spreadsheet using Python?
  12. How do you add charts or graphs to an Excel spreadsheet using Python?
  13. What is web scraping?
  14. How do you perform web scraping in Python?
  15. What libraries are commonly used for web scraping in Python?
  16. How do you install the required libraries for web scraping in Python?
  17. How do you extract data from HTML using web scraping in Python?
  18. How do you extract data from JSON using web scraping in Python?
  19. How do you handle pagination when web scraping in Python?
  20. How do you handle login and authentication when web scraping in Python?
  21. How do you handle dynamic websites or websites with JavaScript when web scraping in Python?
  22. How do you store the scraped data in a CSV file using Python?
  23. How do you store the scraped data in a database using Python?
  24. How do you handle errors and exceptions when web scraping in Python?
  25. What are some ethical considerations when performing web scraping in Python?

10. Viva Questions on ” working with PDF, word and JSON files  “

  1. What is a PDF file? How can you manipulate it using Python?
  2. How can you read text from a PDF file using Python?
  3. How can you extract images from a PDF file using Python?
  4. How can you extract metadata from a PDF file using Python?
  5. How can you merge multiple PDF files into a single PDF using Python?
  6. How can you split a PDF file into multiple smaller PDF files using Python?
  7. How can you add text or watermark to a PDF file using Python?
  8. How can you convert a PDF file to a different format, such as Word or HTML, using Python?
  9. How can you create a new PDF file from scratch using Python?
  10. How can you encrypt or password-protect a PDF file using Python?
  11. What is a Word document? How can you manipulate it using Python?
  12. How can you read text from a Word document using Python?
  13. How can you extract images from a Word document using Python?
  14. How can you modify the formatting or styles of a Word document using Python?
  15. How can you convert a Word document to a different format, such as PDF or HTML, using Python?
  16. How can you create a new Word document from scratch using Python?
  17. How can you add tables or charts to a Word document using Python?
  18. How can you replace or search for specific text in a Word document using Python?
  19. What is JSON? How can you read JSON data using Python?
  20. How can you write JSON data to a file using Python?
  21. How can you parse and manipulate nested JSON structures using Python?
  22. How can you convert JSON data to Python objects and vice versa?
  23. How can you validate JSON data against a schema using Python?
  24. How can you pretty-print or format JSON data for better readability using Python?
  25. How can you handle errors or exceptions when working with JSON files in Python?