You are on page 1of 53

Name : Bhagwat Shreyas Ravindra

Roll no : 23205
1. Python installation and configuration with windows.

To install Python on Windows and configure it properly, you can follow these steps:
1. Download Python Installer:
Go to the official Python website: python.org.
Navigate to the Downloads section.
Download the latest version of Python for Windows. Choose either the 64-bit
or 32-bit installer based on your system architecture.
2. Run the Installer:
Once the installer is downloaded, double-click on it to run.
Check the box that says "Add Python x.x to PATH". This will make Python
accessible from the command line.
Click "Install Now" to start the installation process.
3. Verify Installation:
After installation, open the Command Prompt (CMD).
Type python --version and press Enter. This should display the installed
Python version. If not, there might be an issue with the PATH configuration.
4. Set PATH Variable (if necessary):
If Python is not recognized in the command prompt, you might need to
manually add it to the PATH variable.
Go to Control Panel > System and Security > System > Advanced System
Settings > Environment Variables.
Under "System Variables", find the "Path" variable and select it, then click
"Edit".
Add the path to your Python installation directory (e.g., C:\Python39) to the
list of paths. Each path should be separated by a semicolon.
Click "OK" to save the changes.
5. Test Installation:
Close and reopen the Command Prompt.
Type python --version again. It should now display the installed Python
version without any issues.

1
Name : Bhagwat Shreyas Ravindra
Roll no : 23205
2.Programs for understanding the data types, control flow statements, blocks
and loops

I. Data type List, Tuple, Set, Dictionary and operation on these data types.

# List operations
my_list = [8, 4, 2, 1, 6]

# Adding elements to the list


my_list.append(61)
my_list.extend([9, 5, 4])
my_list.insert(0, 0)

# Removing elements from the list


my_list.remove(3)
popped_element = my_list.pop()
del my_list[1]

# Accessing elements in the list


print("List:", my_list)

# Tuple operations
print("\nTuple operations")
my_tuple = (1, 2, 3, 4, 5)

# Accessing elements in the tuple


print("Tuple:", my_tuple)

# Set operations
print("\nSet operations")
my_set = {1, 2, 3, 4, 5}

# Adding elements to the set


my_set.add(6)
my_set.update([7, 8, 9])

# Removing elements from the set


my_set.remove(3)
my_set.discard(10) # Doesn't raise an error if the element is not present
popped_element = my_set.pop() # Removes and returns an arbitrary element

# Accessing elements in the set


print("Set:", my_set)

# Dictionary operations
print("\nDictionary operations")
my_dict = {'a': 1, 'b': 2, 'c': 3}

2
# Adding or updating elements in the dictionary
my_dict['d'] = 4
my_dict.update({'e': 5, 'f': 6})

# Removing elements from the dictionary


del my_dict['b']
popped_value = my_dict.pop('c', None) # Removes and returns the value for the key
'c', if present

# Accessing elements in the dictionary


print("Dictionary:", my_dict)

3
II. Program to find the area of a square

# Function to calculate the area of a square


def square_area(side_length):
return side_length ** 2

# Input side length from the user


side_length = float(input("Enter the length of a side of the square: "))

# Calculate the area


area = square_area(side_length)

# Display the result


print("The area of the square with side length", side_length, "is", area)

III. Program to find the area of rectangle

# Function to calculate the area of a rectangle


def rectangle_area(length, width):
return length * width
# Input length and width from the user
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
# Calculate the area
area = rectangle_area(length, width)
# Display the result
print("The area of the rectangle with length", length, "and width", width, "is", area)

4
IV. Program to Check is a Number is Odd or Even.

# Function to check if a number is odd or even


def check_odd_even(number):
if number % 2 == 0:
return "even"
else:
return "odd"
# Input a number from the user
number = int(input("Enter a number: "))
# Check if the number is odd or even
result = check_odd_even(number)
# Display the result
print("The number", number, "is", result)

V. Program to Check is a Number is Positive, Negative or Zero

# Function to check if a number is positive, negative, or zero


def check_positive_negative_zero(number):
if number > 0:
return "positive"
elif number < 0:
return "negative"
else:
return "zero"
# Input a number from the user
number = float(input("Enter a number: "))
# Check if the number is positive, negative, or zero
result = check_positive_negative_zero(number)

# Display the result


print("The number", number, "is", result)

5
VI. Python Program to Check is a Number is Prime or not Prime

# Function to check if a number is prime


def is_prime(number):
if number <= 1:
return False
elif number == 2:
return True
elif number % 2 == 0:
return False
else:
for i in range(3, int(number ** 0.5) + 1, 2):
if number % i == 0:
return False
return True
# Input a number from the user
number = int(input("Enter a number: "))

# Check if the number is prime or not prime


if is_prime(number):
print(number, "is a prime number")
else:
print(number, "is not a prime number")

VII. Python Program to Check Year is Leap or Non-Leap.

def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
year = int(input("Enter a year: "))
if is_leap_year(year):
print(year, "is a leap year")
else:
print(year, "is not a leap year")

6
VIII. Python Program to Check Armstrong Number

def is_armstrong(number):
num_str = str(number)
num_digits = len(num_str)
armstrong_sum = sum(int(digit) ** num_digits for digit in num_str)
return armstrong_sum == number

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


if is_armstrong(number):
print(number, "is an Armstrong number")
else:
print(number, "is not an Armstrong number")

IX. Write a program to print the sum of natural numbers using recursion

def sum_of_natural_numbers(n):
if n <= 1:
return n
else:
return n + sum_of_natural_numbers(n - 1)
limit = int(input("Enter the upper limit: "))

if limit < 0:
print("Please enter a non-negative integer.")
else:
result = sum_of_natural_numbers(limit)

# Display the result


print("The sum of natural numbers up to", limit, "is:", result)

7
X. Write a program to accept decimal number and print its octal, binary and
hexadecimal.

def decimal_to_octal(decimal_number):
return oct(decimal_number)

def decimal_to_binary(decimal_number):
return bin(decimal_number)

def decimal_to_hexadecimal(decimal_number):
return hex(decimal_number)

decimal_number = int(input("Enter a decimal number: "))

# Convert the decimal number to octal, binary, and hexadecimal


octal_representation = decimal_to_octal(decimal_number)
binary_representation = decimal_to_binary(decimal_number)
hexadecimal_representation = decimal_to_hexadecimal(decimal_number)

# Display the representations


print("Octal representation:", octal_representation)
print("Binary representation:", binary_representation)
print("Hexadecimal representation:", hexadecimal_representation)

8
XI. Write a program to check whether entered string &amp; number is
palindrome or not.

def is_palindrome_string(s):
return s == s[::-1]

def is_palindrome_number(n):
return str(n) == str(n)[::-1]

# Input a string or number from the user


input_str = input("Enter a string or number: ")

# Check if the input is a palindrome


if input_str.isdigit():
if is_palindrome_number(int(input_str)):
print("The entered number is a palindrome.")
else:
print("The entered number is not a palindrome.")
else:
if is_palindrome_string(input_str):
print("The entered string is a palindrome.")
else:
print("The entered string is not a palindrome.")

9
Name : Bhagwat Shreyas Ravindra
Roll no : 23205
3.Programs for understanding functions, use of built in functions, user
defined functions

I. Python Program to Find the Addition, Subtraction,Multiplication and Division


of two numbers, make the Function for it.

def add(a, b):


return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

def divide(a, b):


if b == 0:
return "Cannot divide by zero"
else:
return a / b

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))

addition_result = add(num1, num2)


subtraction_result = subtract(num1, num2)
multiplication_result = multiply(num1, num2)
division_result = divide(num1, num2)

print("Addition:", addition_result)
print("Subtraction:", subtraction_result)
print("Multiplication:", multiplication_result)
print("Division:", division_result)

10
II. Python Program to find the Factorial of a number. Using recursive function.

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
number = int(input("Enter a number: "))
if number < 0:
print("Factorial is not defined for negative numbers.")
else:
result = factorial(number)
print("The factorial of", number, "is:", result)

III. Python Program to display the multiplication Table. Make the Function for
it.
def multiplication_table(number, limit=10):
print(f"Multiplication Table for {number}:")
for i in range(1, limit + 1):
print(f"{number} x {i} = {number * i}")

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


multiplication_table(number)

11
IV. Python program to demonstrate decorators and generators

# Decorator function to measure execution time


import time
def measure_time(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Execution time of {func.__name__}: {end_time - start_time} seconds")
return result
return wrapper

# Generator function to generate Fibonacci sequence


def fibonacci_sequence(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b

# Applying decorator to the generator function


@measure_time
def generate_fibonacci_sequence(n):
for num in fibonacci_sequence(n):
print(num)

# Example usage
generate_fibonacci_sequence(10)

12
Name : Bhagwat Shreyas Ravindra
Roll no : 23205
4.Programs to use existing modules, packages and creating modules,
Packages

I. Python program shows use of built in module and packages at least 30 built in
functions

# Importing built-in modules


import math
import random
import os
import sys
import datetime
import json
import itertools
import re
import urllib.request
import time
import collections
import string
import calendar
import zlib
import hashlib
import heapq
import fractions
import textwrap
import platform
import copy
import functools
import base64
import csv
import xml.etree.ElementTree as ET
import pickle
import argparse
import subprocess

# Using built-in functions


print("Built-in Functions:")
print("1. Absolute value of -10:", abs(-10))
print("2. Sum of [1, 2, 3]:", sum([1, 2, 3]))
print("3. Length of 'Hello':", len("Hello"))
print("4. Maximum of 4, 6, 2:", max(4, 6, 2))
print("5. Minimum of 4, 6, 2:", min(4, 6, 2))
print("6. Power of 2^3:", pow(2, 3))
print("7. Round 3.14159 to 2 decimal places:", round(3.14159, 2))
print("8. Square root of 25:", math.sqrt(25))
print("9. Random integer between 1 and 100:", random.randint(1, 100))
print("10. Current working directory:", os.getcwd())

13
print("11. System platform:", sys.platform)
print("12. Current date and time:", datetime.datetime.now())
print("13. JSON encoding of {'name': 'John'}:", json.dumps({'name': 'John'}))
print("14. Cartesian product of [(1, 2), ('a', 'b')]:", list(itertools.product([1, 2], ['a', 'b'])))
print("15. Match 'apple' in 'pineapple':", re.match('apple', 'pineapple'))
print("16. Retrieve URL:", urllib.request.urlopen("https://www.example.com"))
print("17. Current timestamp:", time.time())
print("18. Counter of characters in 'hello':", collections.Counter("hello"))
print("19. Strip punctuation from 'Hello, World!':", "Hello,
World!".translate(str.maketrans('', '', string.punctuation)))
print("20. Calendar of January 2024:", calendar.month(2024, 1))
print("21. Compress 'Hello, World!':", zlib.compress(b"Hello, World!"))
print("22. MD5 hash of 'Hello':", hashlib.md5(b"Hello").hexdigest())
print("23. Smallest 3 numbers in [5, 2, 8, 0, 1]:", heapq.nsmallest(3, [5, 2, 8, 0, 1]))
print("24. Greatest common divisor of 12 and 15:", fractions.gcd(12, 15))
print("25. Wrap text to 20 characters:", textwrap.wrap("Lorem ipsum dolor sit amet,
consectetur adipiscing elit.", 20))
print("26. Python version:", platform.python_version())
print("27. Shallow copy of [1, 2, 3]:", copy.copy([1, 2, 3]))
print("28. Reduce function to add [1, 2, 3, 4]:", functools.reduce(lambda x, y: x + y,
[1, 2, 3, 4]))
print("29. Base64 encoding of 'Hello':", base64.b64encode(b"Hello").decode('utf-8'))
print("32. Pickle serialize [1, 2, 3]:")
data = [1, 2, 3]
serialized = pickle.dumps(data)
print(serialized)

14
II. Python program to create module of Arithmetic operation

 Create a Python file named arithmetic.py.


 Define functions for different arithmetic operations in this file.
 Import this module into another Python script and use the functions defined
within it.

# arithmetic.py

def add(x, y):


"""Return the sum of x and y."""
return x + y

def subtract(x, y):


"""Return the result of subtracting y from x."""
return x - y

def multiply(x, y):


"""Return the product of x and y."""
return x * y

def divide(x, y):


"""Return the result of dividing x by y."""
if y == 0:
raise ValueError("Cannot divide by zero!")
return x / y

# main.py

import arithmetic
# Perform arithmetic operations
result_add = arithmetic.add(5, 3)
result_subtract = arithmetic.subtract(10, 4)
result_multiply = arithmetic.multiply(6, 7)
result_divide = arithmetic.divide(20, 5)

# Display results
print("Addition:", result_add)
print("Subtraction:", result_subtract)
print("Multiplication:", result_multiply)
print("Division:", result_divide)

15
III. Python program to create package and use package.

 Create a directory named my_package.


 Inside my_package, create two files: __init__.py and operations.py.
 Define some functions in operations.py.
 In __init__.py, import these functions to make them accessible when the package
is imported.
 Finally, create a script outside the package directory to use the package.

# operations.py

def add(x, y):


"""Return the sum of x and y."""
return x + y

def subtract(x, y):


"""Return the result of subtracting y from x."""
return x - y

def multiply(x, y):


"""Return the product of x and y."""
return x * y

def divide(x, y):


"""Return the result of dividing x by y."""
if y == 0:
raise ValueError("Cannot divide by zero!")
return x / y

# main.py

from my_package import add, subtract, multiply, divide


# Perform arithmetic operations
result_add = add(5, 3)
result_subtract = subtract(10, 4)
result_multiply = multiply(6, 7)
result_divide = divide(20, 5)

# Display results
print("Addition:", result_add)
print("Subtraction:", result_subtract)
print("Multiplication:", result_multiply)
print("Division:", result_divide)

16
Name : Bhagwat Shreyas Ravindra
Roll no : 23205
5. Programs for implementations of all object-oriented concepts like class,
method, inheritance, polymorphism etc. (Real life examples must be covered for
the implementation of object oriented concepts)

I. Create class called, library with data attributes like Acc-number publisher,
title and author, the methods of the class should include a) Read ( ) - Acc-
number, title, author, publisher. b) Compute ( ) - to accept the number of day
late, calculate and display the fine charged at the rate of Rupees 5/- per day. c)
Display the data.

class Library:
def __init__(self, acc_number, publisher, title, author):
self.acc_number = acc_number
self.publisher = publisher
self.title = title
self.author = author
def read(self):
print("Acc-number:", self.acc_number)
print("Title:", self.title)
print("Author:", self.author)
print("Publisher:", self.publisher)
def compute(self, days_late):
fine = days_late * 5
print("Fine charged: Rs.", fine)
def display_data(self):
print("Acc-number:", self.acc_number)
print("Title:", self.title)
print("Author:", self.author)
print("Publisher:", self.publisher)

# Example usage:
book1 = Library(8421699, "Developer", "Java", "Author Shrey")
book1.read() # Display book information
book1.compute(3) # Calculate and display fine for 3 days late
book1.display_data() # Display book information again

17
II. Python program for Bank demo Deposit, withdraw functions and validation
like cannot withdraw amount greater than available balance if password is
wrong for more than 3 times block that account.

class BankAccount:
def __init__(self, account_number, balance, password):
self.account_number = account_number
self.balance = balance
self.password = password
self.attempts = 0
self.blocked = False

def deposit(self, amount):


if not self.blocked:
self.balance += amount
print("Amount deposited. New balance:", self.balance)
else:
print("Account is blocked. Cannot perform transactions.")

def withdraw(self, amount, password):


if not self.blocked:
if self.password == password:
if amount <= self.balance:
self.balance -= amount
print("Amount withdrawn. New balance:", self.balance)
else:
print("Insufficient balance.")
else:
self.attempts += 1
print("Incorrect password. Attempts remaining:", 3 - self.attempts)
if self.attempts >= 3:
print("Account blocked due to multiple incorrect password attempts.")
self.blocked = True
else:
print("Account is blocked. Cannot perform transactions.")

account1 = BankAccount("8421699", 5000, "shrey7199")

# Valid deposit
account1.deposit(1000)
# Valid withdraw
account1.withdraw(2000, "shrey7199")

# Incorrect password attempts


account1.withdraw(1000, "wrongpass")
account1.withdraw(1000, "wrongpass")
account1.withdraw(1000, "wrongpass") # Account will be blocked after this attempt
account1.withdraw(1000, "shrey7199") # Account is blocked. Cannot perform
transactions.
account1.deposit(500) # Account is blocked. Cannot perform transactions.

18
19
III. Python program for Inheritance demo covering all type of inheritance

# Single Inheritance
class Parent1:
def show_parent(self):
print("Parent method")

class Child1(Parent1):
def show_child(self):
print("Child method")

# Multiple Inheritance
class A:
def method_a(self):
print("Method A")

class B:
def method_b(self):
print("Method B")

class C(A, B):


def method_c(self):
print("Method C")

# Hierarchical Inheritance
class Base:
def method_base(self):
print("Base method")

class Derived1(Base):
def method_derived1(self):
print("Derived1 method")

class Derived2(Base):
def method_derived2(self):
print("Derived2 method")

# Multilevel Inheritance
class Grandparent:
def method_grandparent(self):
print("Grandparent method")
class Parent2(Grandparent):
def method_parent(self):
print("Parent method")
class Child2(Parent2):
def method_child(self):
print("Child method")
print("Single Inheritance:")

child_obj = Child1()

20
child_obj.show_parent() # Accessing parent method
child_obj.show_child() # Accessing child method

print("\nMultiple Inheritance:")

c_obj = C()
c_obj.method_a() # Accessing method from class A
c_obj.method_b() # Accessing method from class B
c_obj.method_c() # Accessing method from class C

print("\nHierarchical Inheritance:")

derived1_obj = Derived1()
derived1_obj.method_base() # Accessing method from base class
derived1_obj.method_derived1() # Accessing method from derived class

derived2_obj = Derived2()
derived2_obj.method_base() # Accessing method from base class
derived2_obj.method_derived2() # Accessing method from derived class

print("\nMultilevel Inheritance:")

child_obj = Child2()
child_obj.method_grandparent() # Accessing method from grandparent class
child_obj.method_parent() # Accessing method from parent class
child_obj.method_child() # Accessing method from child class

21
IV. Python program for Polymorphism Demo (Operator overloading, Method
overloading)

# Operator Overloading
class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def __add__(self, other):


return Point(self.x + other.x, self.y + other.y)

def __str__(self):
return f"({self.x}, {self.y})"

# Method Overloading
class Calculator:
def add(self, a, b):
return a + b

def add(self, a, b, c):


return a + b + c

# Example usage
print("Operator Overloading:")
point1 = Point(1, 2)
point2 = Point(3, 4)
print("Point 1:", point1)
print("Point 2:", point2)
print("Sum of Points:", point1 + point2)

print("\nMethod Overloading:")
calc = Calculator()
#print("Sum of 2 numbers:", calc.add(5, 6))
print("Sum of 3 numbers:", calc.add(5, 6, 7))

22
Name : Bhagwat Shreyas Ravindra
Roll no : 23205
6. Programs for parsing of data, validations like Password, email, URL, etc.

Parsing Data:

 JSON Parsing:
import json
# Parse JSON data
json_data = '{"name": "John", "age": 30}'
parsed_data = json.loads(json_data)
print(parsed_data)

 XML Parsing:
import xml.etree.ElementTree as ET
# Parse XML data
xml_data = '<person><name>John</name><age>30</age></person>'
root = ET.fromstring(xml_data)
for child in root:
print(child.tag, child.text)

 CSV Parsing:
import csv
# Parse CSV data
csv_data = "name,age\nJohn,30\nJane,25"
reader = csv.reader(csv_data.splitlines())
for row in reader:
print(row)

23
 Email Validation:
import re
def validate_email(email):
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
return re.match(pattern, email) is not None

email = 'example@example.com'
if validate_email(email):
print("Valid email")
else:
print("Invalid email")

 URL Validation:
import re
def validate_url(url):
pattern = r'^https?://(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,6}(?:/[^/]*)*$'
return re.match(pattern, url) is not None
url = 'https://www.example.com'
if validate_url(url):
print("Valid URL")
else:
print("Invalid URL")

 Password Validation:
import re
def validate_password(password):
# Add your password validation logic here
# Example: At least 8 characters, with at least one uppercase letter, one lowercase
letter, and one digit
return re.match(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$', password) is not
None
password = 'Password123'
if validate_password(password):
print("Valid password")
else:
print("Invalid password")

24
Name : Bhagwat Shreyas Ravindra
Roll no : 23205
7. Programs for Pattern finding should be covered.

def print_star_pattern(rows):
for i in range(1, rows + 1):
print('* ' * i)

print_star_pattern(5)

def print_number_pattern(rows):
num = 1
for i in range(1, rows + 1):
for j in range(1, i + 1):
print(num, end=' ')
num += 1
print()

print_number_pattern(4)

def print_pyramid(rows):
for i in range(0, rows):
for j in range(0, rows - i - 1):
print(end=" ")
for j in range(0, i + 1):
print("*", end=" ")
print()

print_pyramid(5)

def print_diamond(rows):
for i in range(0, rows):
for j in range(0, rows - i - 1):
print(end=" ")
for j in range(0, i + 1):
print("*", end=" ")
print()
for i in range(rows - 2, -1, -1):
for j in range(0, rows - i - 1):
print(end=" ")
for j in range(0, i + 1):
print("*", end=" ")
print()

print_diamond(5)

25
Name : Bhagwat Shreyas Ravindra
Roll no : 23205
8. Multithreading & Exception handling.

I. Programs covering all the aspects of Exception handling, user defined


exception, Multithreading should be covered.

import threading
import time

# User-defined Exception
class CustomException(Exception):
def __init__(self, message):
super().__init__(message)

# Function demonstrating exception handling


def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("Error: Division by zero!")
else:
print("Result of division:", result)
finally:
print("Division operation completed.")

# Thread class for demonstrating multithreading


class MyThread(threading.Thread):
def __init__(self, thread_id, name, counter):
threading.Thread.__init__(self)
self.thread_id = thread_id
self.name = name
self.counter = counter

def run(self):
print("Starting " + self.name)
print_time(self.name, self.counter, 5)
print("Exiting " + self.name)

# Function to print time


def print_time(thread_name, delay, counter):
while counter:
time.sleep(delay)
print("%s: %s" % (thread_name, time.ctime(time.time())))
counter -= 1

# Main function
if __name__ == "__main__":

26
# Exception handling
divide(10, 2) # No exception
divide(10, 0) # ZeroDivisionError

# User-defined exception
try:
raise CustomException("This is a custom exception.")
except CustomException as e:
print("Custom Exception caught:", e)

# Multithreading
# Create new threads
thread1 = MyThread(1, "Thread-1", 1)
thread2 = MyThread(2, "Thread-2", 2)

# Start new Threads


thread1.start()
thread2.start()

thread1.join()
thread2.join()

print("Exiting Main Thread")

27
II. Python program to perform Exception handling (Divide by zero Exception)

def divide(x, y):


try:
result = x / y
print("Result of division:", result)
except ZeroDivisionError:
print("Error: Division by zero!")

# Main function
if __name__ == "__main__":
# Example division operations
divide(10, 2) # No exception
divide(10, 0) # ZeroDivisionError

III. Python program for Integer Input Validation with Exception Handling
(Example of ValueError Exception).
def get_integer_input(prompt):
while True:
try:
user_input = int(input(prompt))
return user_input
except ValueError:
print("Error: Please enter a valid integer.")
# Main function
if __name__ == "__main__":
try:
# Get an integer input from the user
number = get_integer_input("Enter an integer: ")
print("You entered:", number)
except KeyboardInterrupt:
print("\nUser interrupted the program.")
except Exception as e:
print("An error occurred:", e)

28
IV. Program for IndexError Exception in Python with Example.
def access_list_element(index):
my_list = [1, 2, 3, 4, 5]
try:
value = my_list[index]
print("Value at index", index, ":", value)
except IndexError:
print("Error: Index", index, "is out of range.")

# Main function
if __name__ == "__main__":
try:
# Access elements from the list
access_list_element(2) # Valid index
access_list_element(10) # Invalid index
except Exception as e:
print("An error occurred:", e)

29
V. Python Program for Raising User Generated Exception a) Write user
defined exception program in python which will except age as an input from
the user and check whether the user is eligible for voting or not. If age&lt;18
it should raise the exception as ‘Not eligible for voting’

# Define custom exception class


class UnderAgeException(Exception):
def __init__(self, message="Not eligible for voting"):
self.message = message
super().__init__(self.message)

# Function to check voting eligibility


def check_voting_eligibility(age):
if age < 18:
raise UnderAgeException()
else:
print("You are eligible for voting.")

# Main program
def main():
try:
age = int(input("Enter your age: "))
check_voting_eligibility(age)
except ValueError:
print("Please enter a valid age (an integer).")
except UnderAgeException as e:
print(e)

if __name__ == "__main__":
main()

30
VI. Python Program for Multithreading-- Write multithread program, where
one thread prints square of a number and another thread prints cube of
numbers. Also display the total time taken for execution.

import threading
import time

def print_square(num):
print(f"Square of {num}: {num*num}")

def print_cube(num):
print(f"Cube of {num}: {num*num*num}")

if __name__ == "__main__":
num = int(input("Enter a number: "))

start_time = time.time()

square_thread = threading.Thread(target=print_square, args=(num,))


cube_thread = threading.Thread(target=print_cube, args=(num,))

square_thread.start()
cube_thread.start()

square_thread.join()
cube_thread.join()

end_time = time.time()

print(f"Total time taken: {end_time - start_time} seconds")

31
Name : Bhagwat Shreyas Ravindra
Roll no : 23205
9.Programs demonstrating the IO operations like reading from file, writing
into file from different file types like data file, binary file, etc.

I. Python Program for writing log and change the log level.

import logging

# Set up logging
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger()

def change_log_level(level):
"""Function to change the log level dynamically."""
numeric_level = getattr(logging, level.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError('Invalid log level: %s' % level)
logger.setLevel(numeric_level)
print(f"Log level changed to {level.upper()}.")

def main():
logger.debug("This is a debug message.")
logger.info("This is an info message.")
logger.warning("This is a warning message.")
logger.error("This is an error message.")
logger.critical("This is a critical message.")

if __name__ == "__main__":
main()

32
II. Python Program for read functions and write functions such as read(),
readline() and readlines() and write() and writelines()

def read_file(filename):
"""Function to read from a file using different read functions."""
try:
with open(filename, 'r') as file:
# Read the entire file
print("Contents of the file (read()):")
print(file.read())

# Reset file pointer


file.seek(0)

# Read line by line


print("\nContents of the file (readline()):")
print(file.readline(), end='') # Read and print the first line
print(file.readline(), end='') # Read and print the second line

# Reset file pointer


file.seek(0)

# Read all lines into a list


print("\nContents of the file (readlines()):")
lines = file.readlines()
for line in lines:
print(line, end='')

except FileNotFoundError:
print(f"Error: File '{filename}' not found.")

def write_file(filename, data):


"""Function to write to a file using different write functions."""
with open(filename, 'w') as file:
# Write a single string
file.write(data)

# Write a list of strings


# file.writelines(data_list)

if __name__ == "__main__":
filename = "example.txt"

# Write data to file


data = "Hello, this is a test.\nThis is the second line."
write_file(filename, data)
print(f"Data written to '{filename}' successfully.")

# Read data from file


read_file(filename)

33
34
III. Write a program to read the contents of file and display occurrence of given
character.
def count_occurrences(filename, char):

"""Function to count occurrences of a given character in a file."""

try:
with open(filename, 'r') as file:
content = file.read()
occurrences = content.count(char)
print(f"The character '{char}' occurs {occurrences} time(s) in the file
'{filename}'.")

except FileNotFoundError:
print(f"Error: File '{filename}' not found.")

if __name__ == "__main__":
filename = "example.txt" # Replace with your file name
character_to_count = 'e' # Replace with the character you want to count
count_occurrences(filename, character_to_count)

35
IV. Python program on binary data file showing the file operations (read, search,
update, delete)
import os

def read_binary_file(filename):
"""Function to read a binary file."""
try:
with open(filename, 'rb') as file:
data = file.read()
return data
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
return None

def search_binary_file(filename, search_string):


"""Function to search for a pattern in a binary file."""
data = read_binary_file(filename)
if data:
if search_string in data:
print(f"Pattern '{search_string}' found in the file '{filename}'.")
else:
print(f"Pattern '{search_string}' not found in the file '{filename}'.")

def update_binary_file(filename, search_string, replace_string):


"""Function to update occurrences of a pattern in a binary file."""
data = read_binary_file(filename)
if data:
if search_string in data:
updated_data = data.replace(search_string, replace_string)
with open(filename, 'wb') as file:
file.write(updated_data)
print(f"Pattern '{search_string}' replaced with '{replace_string}' in the file
'{filename}'.")
else:
print(f"Pattern '{search_string}' not found in the file '{filename}'.")

def delete_binary_file(filename):
"""Function to delete a binary file."""
try:
os.remove(filename)
print(f"File '{filename}' deleted successfully.")
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")

if __name__ == "__main__":
filename = "binary_data.bin" # Replace with your binary file name

# Read binary file


print("Reading binary file:")
data = read_binary_file(filename)

36
if data:
print(f"Data read from '{filename}':")
print(data)

# Search for pattern in binary file


print("\nSearching pattern in binary file:")
search_string = b"pattern"
search_binary_file(filename, search_string)

# Update pattern in binary file


print("\nUpdating pattern in binary file:")
search_string = b"pattern"
replace_string = b"replacement"
update_binary_file(filename, search_string, replace_string)

# Delete binary file


print("\nDeleting binary file:")
delete_binary_file(filename)

37
Name : Bhagwat Shreyas Ravindra
Roll no : 23205
10.Programs to perform searching, adding, updating the content from the file.
import os

def search_content(file_path, search_term):


with open(file_path, 'r') as file:
for line in file:
if search_term in line:
print(line.strip())

def add_content(file_path, new_content):


with open(file_path, 'a') as file:
file.write(new_content + '\n')

def update_content(file_path, old_content, new_content):


with open(file_path, 'r') as file:
lines = file.readlines()
with open(file_path, 'w') as file:
for line in lines:
if old_content in line:
file.write(new_content + '\n')
else:
file.write(line)

# Example usage:
file_path = 'example.txt'

# Searching
search_term = 'apple'
search_content(file_path, search_term)

# Adding
new_content = 'banana'
add_content(file_path, new_content)

# Updating
old_content = 'apple'
updated_content = 'orange'
update_content(file_path, old_content, updated_content)

38
Name : Bhagwat Shreyas Ravindra
Roll no : 23205
11.Program for performing CRUD operation with MongoDB and Python.

Write a python program using mongoDB database to create a “student”


collection having fields: Student-ID, Name, Course, Mobile, Address. (a
dict with keys like area, city, country, pin) Accept input from user to insert
documents. Write a MongoDB program to delete selected documents given
In.

import pymongo

# Establish a connection to MongoDB


client = pymongo.MongoClient("mongodb://localhost:27017/")

# Create or access the "school" database


db = client["school"]

# Create a collection named "students"


collection = db["students"]

# Function to insert a new student document


def insert_student():
student_id = input("Enter Student ID: ")
name = input("Enter Name: ")
course = input("Enter Course: ")
mobile = input("Enter Mobile: ")
area = input("Enter Area: ")
city = input("Enter City: ")
country = input("Enter Country: ")
pin = input("Enter Pin: ")

student = {
"Student-ID": student_id,
"Name": name,
"Course": course,
"Mobile": mobile,
"Address": {
"area": area,
"city": city,
"country": country,
"pin": pin
}
}

# Insert the document into the collection


collection.insert_one(student)
print("Student added successfully.")

39
# Function to delete documents based on a given condition
def delete_students(condition):
# Delete documents that match the condition
result = collection.delete_many(condition)
print(f"{result.deleted_count} document(s) deleted.")

# Main function
def main():
while True:
print("\n1. Insert Student")
print("2. Delete Student")
print("3. Exit")
choice = input("Enter your choice: ")

if choice == '1':
insert_student()
elif choice == '2':
# Specify the condition to delete documents (example: by name)
name = input("Enter the name of the student to delete: ")
condition = {"Name": name}
delete_students(condition)
elif choice == '3':
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()

40
41
Name : Bhagwat Shreyas Ravindra
Roll no : 23205
12. Basic programs with NumPy as Array, Searching and Sorting, date &amp;
time and String handling
 Using NumPy for Array Operations:
import numpy as np

# Creating NumPy arrays


arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([6, 7, 8, 9, 10])

# Performing array operations


sum_arr = arr1 + arr2
difference_arr = arr1 - arr2
product_arr = arr1 * arr2

print("Sum of arrays:", sum_arr)


print("Difference of arrays:", difference_arr)
print("Product of arrays:", product_arr)

 Searching and Sorting:


# Searching in a list
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1

# Sorting a list
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]

# Example usage
my_list = [64, 34, 25, 12, 22, 11, 90]
target = 25
bubble_sort(my_list)
print("Sorted list:", my_list)
print("Index of", target, ":", linear_search(my_list, target))

42
 Date & Time Handling:
import datetime
# Get current date and time
current_datetime = datetime.datetime.now()
print("Current date and time:", current_datetime)

# Format date and time


formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted date and time:", formatted_datetime)

# Adding days to a date


future_date = current_datetime + datetime.timedelta(days=7)
print("Date after 7 days:", future_date)

 String Handling:
# String manipulation
text = "Hello, world! This is a sample string."

# Splitting string
words = text.split()
print("Words in string:", words)
# Joining string
joined_text = "-".join(words)
print("Joined string:", joined_text)
# Reversing string
reversed_text = text[::-1]
print("Reversed string:", reversed_text)

43
Name : Bhagwat Shreyas Ravindra
Roll no : 23205
13. Programs for series and data frames should be covered. i) Create series and
data frame manually. ii) Read CSV file perform statistical operation.

 Create Series and DataFrame Manually:


import pandas as pd

# Creating a Series manually


series_data = pd.Series([10, 20, 30, 40, 50], index=['A', 'B', 'C', 'D', 'E'])
print("Manually created Series:")
print(series_data)

# Creating a DataFrame manually


data = {'Name': ['John', 'Alice', 'Bob'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']}
df = pd.DataFrame(data)
print("\nManually created DataFrame:")
print(df)

44
 Read CSV File and Perform Statistical Operations:
import pandas as pd

# Read CSV file


df = pd.read_csv('data.csv')

# Display first few rows of the DataFrame


print("\nDataFrame from CSV:")
print(df)

# Statistical operations
mean_values = df.mean()
median_values = df.median()
max_values = df.max()
min_values = df.min()

print("\nMean values:")
print(mean_values)
print("\nMedian values:")
print(median_values)
print("\nMax values:")
print(max_values)
print("\nMin values:")
print(min_values)

45
Name : Bhagwat Shreyas Ravindra
Roll no : 23205
14. Programs to demonstrate data pre-processing and data handling with data
frame (Missing value treatment, rank, sort, treatment for data duplication.)

import pandas as pd
# Sample DataFrame
data = {
'A': [1, 2, None, 4, 5],
'B': ['x', 'y', 'z', 'y', 'x'],
'C': [7, 2, 5, None, 3]
}
df = pd.DataFrame(data)
# Handling missing values
df.fillna(df.mean(), inplace=True) # Filling missing values with column mean
print("After handling missing values:")
print(df)
# Ranking
df['Rank_A'] = df['A'].rank()
print("\nAfter ranking column 'A':")
print(df)

# Sorting
df_sorted = df.sort_values(by='B') # Sorting by column 'B'
print("\nAfter sorting by column 'B':")
print(df_sorted)

# Handling duplicates
df_duplicates = df.drop_duplicates() # Dropping duplicate rows
print("\nAfter handling duplicates:")
print(df_duplicates)

46
Name : Bhagwat Shreyas Ravindra
Roll no : 23205
15. Program for data visualization should be covered. i) Python program for
simple graph(line) generation ii). Python program for Multiline graph iii) Python
program for creating scatter, bar, histogram, pie chart.

import matplotlib.pyplot as plt

# i. Simple line graph generation


def simple_line_graph():
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Graph')
plt.show()

47
# ii. Multiline graph
def multiline_graph():
x = [1, 2, 3, 4, 5]
y1 = [2, 3, 5, 7, 11]
y2 = [1, 4, 9, 16, 25]

plt.plot(x, y1, label='Line 1')


plt.plot(x, y2, label='Line 2')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Multiline Graph')
plt.legend()
plt.show()

48
# iii. Scatter plot
def scatter_plot():
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

plt.scatter(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot')
plt.show()
scatter_plot()

49
# Bar chart
def bar_chart():
x = ['A', 'B', 'C', 'D', 'E']
y = [10, 20, 15, 25, 30]

plt.bar(x, y)
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Chart')
plt.show()
bar_chart()

50
# Histogram
import matplotlib.pyplot as plt

def histogram():
data = [1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5]

plt.hist(data, bins=5)
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Histogram')
plt.show()
histogram()

51
# Pie chart
import matplotlib.pyplot as plt

def pie_chart():
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]

plt.pie(sizes, labels=labels, autopct='%1.1f%%')


plt.title('Pie Chart')
plt.show()

pie_chart()

52
53

You might also like