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

Focp Practical

Uploaded by

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

Focp Practical

Uploaded by

TUSHAR
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

School of Engineering & Technology

Fundamentals of Computer Programming lab


ENCS151
(2024-25)

Submitted By Submitted To
DIVYANSHU DEEP Mr. Deepak Kaushik
Roll NO = 2401010215
Program Name = B.tech CSE Core
Semester 1st
INDEX
S.N EXPERIMENTS Page DATE signature
no
1 Write a Python function that takes two numbers as input and returns a 06-
string indicating whether the first number is greater than, less than, or 1 09-
equal to the second number using comparison operators. 24
2 Create a Python program that functions as a calculator. It should support 06-
addition, subtraction, multiplication, division, and modulus operations. 09-
2-3
Maintain a history of calculations performed and provide an option to 24
display the history. Implement error handling for division by zero.

3 Develop a Python function that takes a list of tuples as input, where each 13-
tuple contains two numbers. For each tuple, compare the numbers using 4-5 09-
all comparison operators and store the results in a dictionary. Return a list 24
of dictionaries for all comparisons.

4 Write a Python program to simulate the operations of basic logic gates 13-
(AND, OR, NOT, NAND, NOR, XOR) using functions. The program should 6-7 09-
take two boolean inputs and the type of gate, then return the result of the 24
logical operation.

5 Create a Python function to check if any permutation of an input string is 13-


a palindrome. For example, the string "civic" is a palindrome, and "ivicc" is 8 09-
a permutation of "civic". The function should return True if any 24
permutation
is a palindrome, otherwise False.
6 Develop a Python function that takes a string and a substring as input and 20-
returns the number of times the substring appears in the string. Implement 9-10 09-
this without using built-in string functions and optimize it for large inputs. 24
7 Write a Python function that performs bitwise operations (AND, OR, XOR) 20-
on two arrays of integers. The function should take two arrays and an 11 09-
operator as input, perform the bitwise operation element-wise, and return 24
the resulting array.

8 Create a class Custom String that mimics some of the built-in string 20-
methods in Python. Implement methods like find(), replace(), split(), and 12-13 09-
join(). The class should be able to handle these operations efficiently and 24
correctly.
9 Create a Python function that finds all prime numbers up to a given number 20-
n. Use nested loops to check for primality and optimize the function to 14-15 09-
handle large inputs efficiently. Additionally, allow the user to break the 24
loop prematurely if they input a specific command.
10 Write a Python program that takes a list of tuples representing student 20-
names and grades, and sorts the list by grades using a lambda function. 15 09-
Ensure that if two students have the same grade, they are sorted by their 24
names.

11 Create a Python function that takes a list of integers and returns a new list 20-
containing only the unique elements of the original list. Use a set to 16 09-
remove duplicates and maintain the order of elements as they appear in 24
the original
list.
12 Write a Python function that takes a string of text and returns a dictionary 27-
with the frequency of each word in the text. The function should handle 17 09-
punctuation and capitalization correctly and provide a case-insensitive 24
count.

13 Create a Python function that takes a tuple as an argument and returns a 27-
new tuple with the elements reversed. Demonstrate the use of tuples as 18 09-
function parameters and unpacking tuple elements within the function. 24
14 Create a Python function that checks if a given string containing 27-
parentheses is balanced. The function should return True if the 19-20 09-
parentheses are balanced and False otherwise. Use a stack to solve this 24
problem and
handle multiple types of parentheses: (), {}, and [].
15 Create a Python function that takes a list of strings and groups them into 4-
anagrams. The function should return a list of lists, where each sublist 20-21 10-
contains words that are anagrams of each other. Use dictionaries to store 24
and group the anagrams efficiently

16 Create a class BankAccount that represents a bank account with attributes 4-


account_number, account_holder, and balance. Implement methods for 21-23 10-
depositing, withdrawing, and checking the balance. Override the str 24
and repr methods to provide meaningful string representations of the
account. Include error handling to prevent overdrafts.

17 Create a class Book with attributes title, author, and isbn. Implement a 4-
class Library that manages a collection of books. Implement methods to 24-26 10-
add, remove, and search for books by title or author. Use file handling to 24
save and load the library collection from a file.

18 Write a Python program that copies the contents of one file to another. 18-
Implement functions to open, read, write, and close files. Use exception 27-29 10-
handling to manage file errors, such as file not found or permission denied. 24
19 Create a base class Employee with attributes name and employee_id. 18-
Derive classes Manager and Developer from Employee, each with 29-31 10-
additional attributes and methods specific to their roles. Override methods 24
where necessary and use polymorphism to write a function that prints the
details
of all employees.
20 Develop a class Item with attributes name, price, and quantity. Create a 18-
class ShoppingCart that manages a collection of items 32-34 10-
24
21 Write a Python program that encrypts and decrypts the contents of a file 18-
using a simple Caesar cipher. 34-35 10-
24
22 Project Title: ROCK PAPER SCISSOR 8-11-
36-37 24
23 Project Title: PASSWORD GENERATOR 22-
38-40 11-
24
24 Project Title: DATA VISUALIZATION 27-
41-43 11-
24
Experiment-1
Write a Python function that takes two numbers as input and returns a
string indicating whether the first number is greater than, less than, or
equal to the second number using comparison operators.

Code:
a=int(input("enter first number:"))

b=int(input("enter second number:"))

if a>b:

print("The first number is greater than second number")

elif a<b:

print("The first number in less than second number")

else:

print("The first number is equal to the second number")

Output:

output:
Experiment 2
Create a Python program that functions as a calculator. It should support
addition, subtraction, multiplication, division, and modulus operations.
Maintain a history of calculations performed and provide an option to
display the history. Implement error handling for division by zero.

code:
print('''Please choose from the following
1. Addition
2.Subtraction
3.Multiplication
4.Division
5.Modulus
6.History
7.Quit''')

def add(a,b):
c=a+b
print("Addition of the given numbers is",c)
hist.append(f"{a} + {b} is {c}")

def sub(a,b):
c=a-b
print("Subtraction of the given numbers is",c)
hist.append(f"{a} - {b} is {c}")

def mul(a,b):
c=a*b
print("Multiplication of the given numbers is",c)
hist.append(f"{a} * {b} is {c}")

def div(a,b):
if b == 0:
print("Error: division by zero is not allowed")
hist.append(f"{a} / {b} failed due to division by zero")
else:
c= a/b
print("Divison of the given numbers is",c)
hist.append(f"{a} / {b} is {c}")

def mod(a,b):
c=a%b
print("Modulus of the given numbers is",c)
hist.append(f"{a} % {b} is {c}")

hist = []

while True:
op = int(input("Enter your choice of operator:"))

if op == 7:
break
elif op == 6:
for i in hist:
print(i)
break

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


b= int(input("Enter second number:"))

if op==1:
add(a,b)

elif op==2:
sub(a,b)

elif op==3:
mul(a,b)

elif op == 4:
div(a,b)

elif op==5:
mod(a,b)
Output:
Experiment 3
Develop a Python function that takes a list of tuples as input, where each
tuple contains two numbers. For each tuple, compare the numbers using
all comparison operators and store the results in a dictionary. Return a list
of dictionaries for all comparisons.

Code:
if compare_tuples(tuple_list):
"""
Takes a list of tuples, compares the numbers in each tuple using all comparison
operators,
and returns a list of dictionaries containing the results.

:param tuple_list: List of tuples, each containing two numbers


:return: List of dictionaries with comparison results
"""
results = []

for a, b in tuple_list:
comparison_results = {
'equal': a == b,
'not_equal': a != b,
'less_than': a < b,
'greater_than': a > b,
'less_than_or_equal': a <= b,
'greater_than_or_equal': a >= b}
results.append(comparison_results)

return results

# Example usage
input_tuples = [(3, 5), (7, 7), (10, 2)]
output = compare_tuples(input_tuples)
print(output)
output:
Experiment-4
Write a Python program to simulate the operations of basic logic gates
(AND, OR, NOT, NAND, NOR, XOR) using functions. The program should
take two boolean inputs and the type of gate, then return the result of the
logical operation.

Code:
def logic_gate(input1, input2=None, gate_type="AND"):
"""
Simulates the operation of basic logic gates.

:param input1: First Boolean input


:param input2: Second Boolean input (optional for NOT gate)
:param gate_type: Type of logic gate (AND, OR, NAND, NOR, NOT, XOR)
:return: Result of the logical operation
"""
gate_type = gate_type.upper()

if gate_type == "AND":
return input1 and input2
elif gate_type == "OR":
return input1 or input2
elif gate_type == "NAND":
return not (input1 and input2)
elif gate_type == "NOR":
return not (input1 or input2)
elif gate_type == "XOR":
return input1 ^ input2
elif gate_type == "NOT":
if input2 is not None:
raise ValueError("NOT gate only requires one input.")
return not input1
else:
raise ValueError(f"Unknown gate type: {gate_type}")

# Example usage
try:
print("AND gate:", logic_gate(True, False, "AND")) # False
print("OR gate:", logic_gate(True, False, "OR")) # True
print("NAND gate:", logic_gate(True, False, "NAND")) # True
print("NOR gate:", logic_gate(False, False, "NOR")) # Trueprint("XOR gate:",
logic_gate(True, True, "XOR")) # False
print("NOT gate:", logic_gate(True, gate_type="NOT")) # False
except ValueError as e:
print(e)

Output:
Experiment-5
Create a Python function to check if any permutation of an input string is a
palindrome. For example, the string "civic" is a palindrome, and "ivicc" is a
permutation of "civic". The function should return True if any permutation
is a palindrome, otherwise False.

Code:
def can_form_palindrome(s: str) -> bool: #
Count the frequency of each character
char_count = {}
for char in s:
char_count[char] = char_count.get(char, 0) + 1

# Check how many characters have an odd frequency


odd_count = sum(1 for count in char_count.values() if count % 2 != 0)

# A string can form a palindrome if at most one character has an odd frequency
return odd_count <= 1

# Example usage print(can_form_palindrome("civic"))


# Output: True print(can_form_palindrome("ivicc"))
# Output: True print(can_form_palindrome("hello"))
# Output: False
print(can_form_palindrome("racecar")) # Output: True

output:
Experiment-6
Develop a Python function that takes a string and a substring as input and
returns the number of times the substring appears in the string.
Implement this without using built-in string functions and optimize it for
large inputs.

Code:
def count_substring(string, substring):
"""
Counts the occurrences of a substring in a string without using built-in string
functions.

Args:
string (str): The main string to search in.
substring (str): The substring to count.

Returns:
int: The number of times the substring appears in the string.
"""
if not string or not substring:
return 0

n = len(string)
m = len(substring)
count = 0

if m > n:
return 0 # Substring is longer than the string, so it can't appear

# Sliding window approach


i=0
while i <= n - m:
match = True
for j in range(m):
if string[i + j] != substring[j]:
match = False
break
if match:
count += 1
i += m # Skip ahead by the length of the substring
else:
i += 1 # Move the window forward break
return count
string = "abababab"
substring = "ab"
print(count_substring(string, substring))

string = "aaaaaa"
substring = "aa"
print(count_substring(string, substring))

output:

Experiment-7
Write a Python function that performs bitwise operations (AND, OR, XOR)
on two arrays of integers. The function should take two arrays and an
operator as input, perform the bitwise operation element-wise, and return
the resulting array.

Code:
Parameters:
- array1 (list of int): The first array of integers.
- array2 (list of int def bitwise_operation(array1, array2, operator):
"""
Perform bitwise operations (AND, OR, XOR) on two arrays of integers.

): The second array of integers.


- operator (str): The bitwise operator ('AND', 'OR', 'XOR').

Returns:
- list of int: Resulting array after performing the operation.

Raises:
- ValueError: If the arrays have different lengths or an invalid operator is provided.
"""
if len(array1) != len(array2):
raise ValueError("Both arrays must have the same length.")

if operator == "AND":
return [a & b for a, b in zip(array1, array2)]
elif operator == "OR":
return [a | b for a, b in zip(array1, array2)]
elif operator == "XOR":
return [a ^ b for a, b in zip(array1, array2)]
else:
raise ValueError("Invalid operator. Use 'AND', 'OR', or 'XOR'.")

# Example usage:
array1 = [1, 2, 3]
array2 = [4, 5, 6]

print("AND:", bitwise_operation(array1, array2, "AND"))


print("OR:", bitwise_operation(array1, array2, "OR"))
print("XOR:", bitwise_operation(array1, array2, "XOR"))

output:
Experiment-8
Create a class CustomString that mimics some of the built-in string
methods in Python. Implement methods like find(), replace(), split(), and
join(). The class should be able to handle these operations efficiently and
correctly.

Code :
def _init_(self, value=""):
if not isinstance(value, str):
raise TypeError("CustomString value must be a string.")
self.value = value class CustomString

def find(self, sub, start=0, end=None):


"""
Mimics the built-in string find() method.
Returns the lowest index of the substring if found, else -1.
"""
end = end if end is not None else len(self.value)
for i in range(start, end - len(sub) + 1):
if self.value[i:i+len(sub)] == sub:
return i
return -1

def replace(self, old, new, count=-1):


"""
Mimics the built-in string replace() method.
Returns a new string with all occurrences of 'old' replaced by 'new'.
"""
result = []
i=0
replaced = 0
while i < len(self.value):
if self.value[i:i+len(old)] == old and (count == -1 or replaced < count):
result.append(new)
i += len(old)
replaced += 1
else:
result.append(self.value[i])
class CustomString:
def _init_(self, value=""):
if not isinstance(value, str):
raise TypeError("CustomString value must be a string.")
self.value = value

def find(self, sub, start=0, end=None):


"""
Mimics the built-in string find() method.
Returns the lowest index of the substring if found, else -1.
"""
end = end if end is not None else len(self.value)
for i in range(start, end - len(sub) + 1):
if self.value[i:i+len(sub)] == sub:
return i
return -1

def replace(self, old, new, count=-1):


"""
Mimics the built-in string replace() method.
Returns a new string with all occurrences of 'old' replaced by 'new'.
"""
result = []
i=0
replaced = 0
while i < len(self.value):
if self.value[i:i+len(old)] == old and (count == -1 or replaced < count):
result.append(new)
i += len(old)
replaced += 1
else:
result.append(self.value[i])

output:
Experiment-9
Create a Python function that finds all prime numbers up to a given number
n. Use nested loops to check for primality and optimize the function to
handle large inputs efficiently. Additionally, allow the user to break the
loop prematurely if they input a specific command.

Code:
import math

def find_primes(n):
primes = []

for num in range(2, n + 1):


user_input = input(f"Check if {num} is prime (type 'stop' to quit):
").strip().lower()
if user_input == 'stop':
print("Prematurely stopped.")
break

is_prime = True

for i in range(2, int(math.sqrt(num)) + 1): if


num % i == 0:
is_prime = False
break
if is_prime:
primes.append(num)

return primes

n = int(input("Enter the number n up to which you want to find prime numbers: "))
primes = find_primes(n)
print(f"Prime numbers up to {n}: {primes}")
output:

EXPERIMENT 10
Write a Python program that takes a list of tuples representing student names and
grades, and sorts the list by grades using a lambda function. Ensure that if two
students have the same grade, they are sorted by their names.

Code:
def sort_students_by_grade(students):

return sorted(students, key=lambda student: (student[1], student[0]))

students= [("Rahul",85), ("John", 75), ("Bob", 92)]

sorted_students = sort_students_by_grade(students)

for student in sorted_students:

print(student)

OUTPUT:
EXPERIMENT 11
Create a Python function that takes a list of integers and returns a new list
containing only the unique elements of the original list. Use a set to
remove duplicates and maintain the order of elements as they appear in
the original list.

Code:
def remove_duplicates(nums):
seen = set()
unique_nums = []

for num in nums:


if num not in seen:
unique_nums.append(num)
seen.add(num)

return unique_nums

original_list = [1, 2, 2, 3, 4, 3, 5, 6, 5]
result = remove_duplicates(original_list)
print(result)

OUTPUT:
EXPERIMENT 12
Write a Python function that takes a string of text and returns a dictionary
with the frequency of each word in the text. The function should handle
punctuation and capitalization correctly and provide a case-insensitive count.

Code:
import string

def word_frequency(text):

text = text.lower()

text = text.translate(str.maketrans("", "", string.punctuation))

words = text.split()

word_count = {}

for word in words:

word_count[word] = word_count.get(word, 0) + 1

return word_count

text = "Hello, world! Hello, everyone. Welcome to the world of Python."

result = word_frequency(text)

print(result)

OUTPUT:
EXPERIMENT 13
Create a Python function that takes a tuple as an argument and returns a
new tuple with the elements reversed. Demonstrate the use of tuples as
function parameters and unpacking tuple elements within the function.

Code:
def reverse_tuple(input_tuple):
*elements, = input_tuple

reversed_tuple = tuple(elements[::-1])
return reversed_tuple

original_tuple = (1, 2, 3, 4, 5)
reversed_tuple = reverse_tuple(original_tuple)

print("Original Tuple:", original_tuple)


print("Reversed Tuple:", reversed_tuple)

OUTPUT:
EXPERIMENT 14
Create a Python function that checks if a given string containing
parentheses is balanced. The function should return True if the
parentheses are balanced and False otherwise. Use a stack to solve this
problem and handle multiple types of parentheses: (), {}, and [].

Code:
def is_balanced(s):
stack = []

parentheses_map = {')': '(', '}': '{', ']': '['}

for char in s:
if char in parentheses_map:
top_element = stack.pop() if stack else '#'

if parentheses_map[char] != top_element:
return False
else:
stack.append(char)

return not stack

print(is_balanced("()"))
print(is_balanced("{[()]}"))
print(is_balanced("{[(])}"))
print(is_balanced("([)]"))
print(is_balanced("((()))"))
print(is_balanced("([{}])"))
print(is_balanced("["))
Output:

EXPERIMENT 15
Create a Python function that takes a list of strings and groups them into
anagrams. The function should return a list of lists, where each sublist
contains words that are anagrams of each other. Use dictionaries to store
and group the anagrams efficiently.

Code:
from collections import defaultdict

def group_anagrams(strs):

anagram_dict = defaultdict(list)

for word in strs:4

sorted_word = ''.join(sorted(word))

anagram_dict[sorted_word].append(word)

return list(anagram_dict.values())
words = ["eat", "tea", "tan", "ate", "nat", "bat"]

result = group_anagrams(words)

print(result)

OUTPUT:

EXPERIMENT 16
Create a class BankAccount that represents a bank account with attributes
account_number, account_holder, and balance. Implement methods for
depositing, withdrawing, and checking the balance. Override the str
and repr methods to provide meaningful string representations of the
account. Include error handling to prevent overdrafts.

Code:
class BankAccount:

def init (self, account_number, account_holder, initial_balance=0.0):

"""Initialize a new bank account."""

self.account_number = account_number

self.account_holder = account_holder

self.balance = initial_balance

def deposit(self, amount):

"""Deposit money into the account."""

if amount <= 0:

raise ValueError("Deposit amount must be positive.")

self.balance += amount

print(f"Deposited ${amount:.2f}. New balance: ${self.balance:.2f}")


def withdraw(self, amount):

"""Withdraw money from the account."""

if amount <= 0:

raise ValueError("Withdrawal amount must be positive.")

if amount > self.balance:

raise ValueError("Insufficient funds for this withdrawal.")

self.balance -= amount

print(f"Withdrew ${amount:.2f}. New balance: ${self.balance:.2f}")

def check_balance(self):

"""Check the current balance."""

return f"Account balance: ${self.balance:.2f}"

def str (self):

"""Return a user-friendly string representation of the account."""

return f"BankAccount({self.account_number}) - {self.account_holder}:


${self.balance:.2f}"

def repr (self):

"""Return a more detailed string representation of the account."""

return f"BankAccount(account_number={self.account_number},
account_holder='{self.account_holder}', balance={self.balance:.2f})"

if name == " main ":

account = BankAccount("123456", "John Doe", 1000.00)


print(account.check_balance())

account.deposit(500)

try:

account.withdraw(200)

except ValueError as e:

print(e)

try:

account.withdraw(1500)

except ValueError as e:

print(e)

print(str(account))

print(repr(account))

OUTPUT:
EXPERIMENT 17
Create a class Book with attributes title, author, and isbn. Implement a
class Library that manages a collection of books. Implement methods to
add, remove, and search for books by title or author. Use file handling to
save and load the library collection from a file.

Code:
import json

class Book:

def init (self, title, author, isbn):

self.title = title

self.author = author

self.isbn = isbn

def repr (self):

return f"Book(title='{self.title}', author='{self.author}', isbn='{self.isbn}')"

def str (self):

return f"Title: {self.title}, Author: {self.author}, ISBN: {self.isbn}"

class Library:

def init (self, filename="library_data.json"):

self.filename = filename

self.books = self.load_books()

def add_book(self, book):


"""Add a new book to the library."""

self.books.append(book)

self.save_books()

print(f"Book '{book.title}' added to the library.")

def remove_book(self, isbn):

"""Remove a book from the library by ISBN."""

book_to_remove = None

for book in self.books:

if book.isbn == isbn:

book_to_remove = book

break

if book_to_remove:

self.books.remove(book_to_remove)

self.save_books()

print(f"Book '{book_to_remove.title}' removed from the library.")

else:

print(f"No book found with ISBN: {isbn}")

def search_by_title(self, title):

"""Search for books by title."""

found_books = [book for book in self.books if title.lower() in book.title.lower()]

return found_books

def search_by_author(self, author):

"""Search for books by author."""


found_books = [book for book in self.books if author.lower() in
book.author.lower()]

return found_books

def save_books(self):

"""Save the library collection to a file."""

with open(self.filename, 'w') as file:

books_data = [{'title': book.title, 'author': book.author, 'isbn': book.isbn} for


book in self.books]

json.dump(books_data, file)

print("Library data saved to file.")

def load_books(self):

"""Load the library collection from a file."""

try:

with open(self.filename, 'r') as file:

books_data = json.load(file)

books = [Book(book['title'], book['author'], book['isbn']) for book in


books_data]

return books

except FileNotFoundError:

print("No library data file found. Starting with an empty library.")

return []

if name == " main ":

library = Library()

book1 = Book("To Kill a Mockingbird", "Harper Lee", "1234567890")


book2 = Book("1984", "George Orwell", "9876543210")

book3 = Book("The Great Gatsby", "F. Scott Fitzgerald", "1112131415")

library.add_book(book1)

library.add_book(book2)

library.add_book(book3)

print("Search results for '1984':", library.search_by_title("1984"))

print("Search results for 'George Orwell':", library.search_by_author("George


Orwell"))

library.remove_book("1234567890")

print("Current Library Collection:")

for book in library.books:

print(book)

OUTPUT:
EXPERIMENT 18
Write a Python program that copies the contents of one file to another.
Implement functions to open, read, write, and close files. Use exception
handling to manage file errors, such as file not found or permission
denied.

Code:
def open_file(filename, mode):

"""Opens a file with the specified mode."""

try:

file = open(filename, mode)

return file

except FileNotFoundError:

print(f"Error: The file '{filename}' was not found.")

return None

except PermissionError:

print(f"Error: Permission denied when trying to open '{filename}'.")

return None

except Exception as e:

print(f"Unexpected error:

{e}") return None

def read_file(file):

"""Reads the content of the file."""

try:

content =

file.read() return

content

except Exception as e:

print(f"Error while reading the file: {e}")

return None

def write_file(file, content):

"""Writes content to the file."""


try:

file.write(content)

except Exception as e:

print(f"Error while writing to the file: {e}")

def close_file(file):

"""Closes the file."""

try:

file.close()

except Exception as e:

print(f"Error while closing the file: {e}")

def copy_file(source_filename, destination_filename):

"""Copies the content from the source file to the destination file."""

source_file = open_file(source_filename, 'r')

if source_file is None:

return # Exit if source file can't be opened

content = read_file(source_file)

if content is None:

close_file(source_file)

return # Exit if reading the file failed

close_file(source_file)

destination_file = open_file(destination_filename,

'w') if destination_file is None:

return # Exit if destination file can't be opened

write_file(destination_file, content)

close_file(destination_file)

print(f"Content copied from '{source_filename}' to '{destination_filename}' successfully.")


# Example usage:

if name == " main ":

source = "source.txt"

destination = "destination.txt"

copy_file(source, destination)

Output :

EXPERIMENT 19
Create a base class Employee with attributes name and employee_id. Derive classes
Manager and Developer from Employee, each with additional attributes and methods
specific to their roles. Override methods where necessary and use polymorphism to write
a function that prints the details of all employees.

Code:

class Employee:

def init (self, name, employee_id):

self.name = name

self.employee_id = employee_id

def print_details(self):

print(f"Employee Name: {self.name}, ID: {self.employee_id}")

class Manager(Employee):

def init (self, name, employee_id, team_size):

super(). init (name, employee_id)

self.team_size = team_size
def print_details(self):

super().print_details() # Call the parent class method

print(f"Manager of a team of {self.team_size} people.")

def manage_team(self):

print(f"{self.name} is managing a team of {self.team_size} people.")

class Developer(Employee):

def init (self, name, employee_id, programming_language):

super(). init (name, employee_id)

self.programming_language = programming_language

def print_details(self):

super().print_details()

print(f"Developer skilled in {self.programming_language}.")

def write_code(self):

print(f"{self.name} is writing code in {self.programming_language}.")

def print_employee_details(employees):

for employee in employees:

employee.print_details()

if name == " main ":

manager = Manager("Alice", 101, 5)

developer = Developer("Bob", 102, "Python")

employees = [manager, developer]


print_employee_details(employees)

manager.manage_team()

developer.write_code()

OUTPUT:
EXPERIMENT 20
Develop a class Item with attributes name, price, and quantity. Create a
class ShoppingCart that manages a collection of items .

Code:
class Item:

def init (self, name, price, quantity):

self.name = name

self.price = price

self.quantity = quantity

def total_price(self):

return self.price * self.quantity

def str (self):

return f"{self.name} (Price: ${self.price:.2f}, Quantity: {self.quantity}, Total:


${self.total_price():.2f})"

class ShoppingCart:

def init (self):

self.items = []

def add_item(self, item):

self.items.append(item)

print(f"Added {item.name} to the cart.")


def remove_item(self, item_name):

for item in self.items:

if item.name == item_name:

self.items.remove(item)

print(f"Removed {item_name} from the cart.")

return

print(f"Item '{item_name}' not found in the cart.")

def calculate_total(self):

return sum(item.total_price() for item in self.items)

def list_items(self):

if not self.items:

print("Your cart is empty.")

else:

print("Items in your cart:")

for item in self.items:

print(item)

def str (self):

if not self.items:

return "Your shopping cart is empty."

else:

item_details = "\n".join(str(item) for item in self.items)

return f"Shopping Cart Details:\n{item_details}\nTotal:


${self.calculate_total():.2f}"
if name == " main ":

item1 = Item("Laptop", 999.99, 1)

item2 = Item("Mouse", 25.50, 2)

item3 = Item("Keyboard", 49.99, 1)

cart = ShoppingCart()

cart.add_item(item1)

cart.add_item(item2)

cart.add_item(item3)

cart.list_items()

print(f"\nTotal cost: ${cart.calculate_total():.2f}")

cart.remove_item("Mouse")

cart.list_items()

print("\nCart Summary:")

print(cart)

Output:
EXPERIMENT 21
Write a Python program that encrypts and decrypts the contents of a file
using a simple Caesar cipher.

Code:
def caesar_cipher(text, shift, mode='encrypt'):

"""

Encrypts or decrypts the text using the Caesar cipher.

Parameters:

- text: The text to be encrypted or decrypted.

- shift: The number of positions to shift.

- mode: 'encrypt' for encryption and 'decrypt' for decryption.

Returns:

- The encrypted or decrypted text.

"""

result = []

for char in text:

if char.isalpha():
# Determine the start of the alphabet (either lowercase or uppercase)

start = ord('A') if char.isupper() else ord('a')

# Shift the character

new_char = chr(start + (ord(char) - start + (shift if mode == 'encrypt' else -


shift)) %

output:
PROJECT 1:

ROCK PAPER SCISSOR

Code:
import random

def get_computer_choice():

choices = ['rock', 'paper', 'scissors']

return random.choice(choices)

def determine_winner(player_choice, computer_choice):

if player_choice == computer_choice:

return "It's a tie!"

if (player_choice == 'rock' and computer_choice == 'scissors') or \ (player_choice

== 'scissors' and computer_choice == 'paper') or \ (player_choice == 'paper'

and computer_choice == 'rock'):

return "You win!"

return "You lose!"

def play_game():

print("Welcome to Rock, Paper, Scissors!")

player_choice = input("Enter your choice (rock, paper, or scissors): ").lower()


if player_choice not in ['rock', 'paper', 'scissors']:

print("Invalid choice. Please choose rock, paper, or scissors.")

return

computer_choice = get_computer_choice()

print(f"Computer's choice: {computer_choice}")

result = determine_winner(player_choice, computer_choice)

print(result)

if name == " main ":

play_game()

OUTPUT:
PROJECT 2:

PASSWORD GENERATOR

Code:
import random

import string

def generate_password(length=12):

lowercase = string.ascii_lowercase

uppercase = string.ascii_uppercase

digits = string.digits

punctuation = string.punctuation

all_characters = lowercase + uppercase + digits + punctuation

password = [

random.choice(lowercase),

random.choice(uppercase),

random.choice(digits),

random.choice(punctuation)

password += random.choices(all_characters, k=length - 4)

random.shuffle(password)
return ''.join(password)

if name == " main ":

length = int(input("Enter the desired password length (e.g., 12): "))

password = generate_password(length)

print(f"Generated password: {password}")

OUTPUT:
PROJECT 3:

DATA VISUALISASTION
Code:

import pandas as pd

import matplotlib.pyplot as plt

import numpy as np

# Creating a sample dataset

np.random.seed(42) # For reproducibility

data = {

'Product Category': ['Electronics', 'Clothing', 'Home Decor', 'Books', 'Toys'],

'Average Sales': np.random.randint(1000, 5000, 5)

# Creating DataFrame from the dataset

df = pd.DataFrame(data)

# Display the DataFrame

print(df)

# Creating a bar chart to visualize average sales by product category

plt.figure(figsize=(10, 6))

plt.bar(df['Product Category'], df['Average Sales'], color='skyblue')


# Adding title and labels

plt.title('Average Sales by Product Category')

plt.xlabel('Product Category')

plt.ylabel('Average Sales ($)')

# Displaying the bar chart

plt.show()import pandas as pd

import matplotlib.pyplot as plt

import numpy as np

# Creating a sample dataset

np.random.seed(42) # For reproducibility

data = {

'Product Category': ['Electronics', 'Clothing', 'Home Decor', 'Books', 'Toys'],

'Average Sales': np.random.randint(1000, 5000, 5)

# Creating DataFrame from the dataset

df = pd.DataFrame(data)

# Display the DataFrame

print(df)

# Creating a bar chart to visualize average sales by product category

plt.figure(figsize=(10, 6))

plt.bar(df['Product Category'], df['Average Sales'], color='skyblue')


# Adding title and labels

plt.title('Average Sales by Product Category')

plt.xlabel('Product Category')

plt.ylabel('Average Sales ($)')

# Displaying the bar chart

plt.show()

output:

You might also like