KEMBAR78
Python Uiet (1) 3 | PDF | Python (Programming Language) | String (Computer Science)
0% found this document useful (0 votes)
15 views61 pages

Python Uiet (1) 3

This document is a practical file for a Python programming course, detailing various experiments and assignments related to Python programming concepts. It includes a structured index of topics covered, such as installing Python, basic functions, creating a calculator, and working with data types like lists and tuples. The file is submitted by Ashish Mahajan to Dr. Neelam Goel at Panjab University, and it outlines practical exercises with corresponding dates and page numbers.

Uploaded by

asmigarg2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views61 pages

Python Uiet (1) 3

This document is a practical file for a Python programming course, detailing various experiments and assignments related to Python programming concepts. It includes a structured index of topics covered, such as installing Python, basic functions, creating a calculator, and working with data types like lists and tuples. The file is submitted by Ashish Mahajan to Dr. Neelam Goel at Panjab University, and it outlines practical exercises with corresponding dates and page numbers.

Uploaded by

asmigarg2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

PYTHON PROGRAMMING (P)

( PEIT501c )

PRACTICAL FILE

Submitted to: Submitted by:


Dr. Neelam Goel Ashish Mahajan
(Asssitant Professor ), IT Roll No: UE228028
UIET, PU Sem-5, IT sec-1, Group 2

Department of Information Technology


University Institute of Engineering and Technology
Panjab University Chandigarh, 2024
INDEX:

S. No. Title Date Page No. Teacher’s


Signature
1 1.1 Install python 02/08/24 1-3

1.2 Explore basic Python Functions 4-7

1.3 Construct a Simple Calculator 8-9

2 2.1 Find Number of Days 09/08/24 10-12

2.2 Display pattern of numbers 12

2.3 Print sum of every fifth number from 0 to 500 13

2.4 Display all the common characters between 14


two strings

2.5 Creating new list from existing lists by 15-16


following some conditions

3 3.1 Perform run length coding on string and return 23/08/24 17-18
the ecnoded string.

3.2 Find_pairs_of_numbers() which accepts a list 18-19


of positive integers with no repetitions and
returns count of pairs of numbers in the list

3.3 Print marks of students according to 19-21


conditions

3.4 Create_largest_number(), which accepts a list 21-22


of numbers and returns the largest number
possible by concatenating the list of numbers

3.5 Create python function check_anagram() () 23-24


which accepts two strings and returns True, if
one string is an anagram of another string.
Otherwise returns False.
4 4.1 Creating a function that takes a list value as 30/08/24 25
an argument and returns a string with all the
items separated by a comma and a space

4.2 Python program to calculate the bill amount 26-27


to be paid by a customer based on the list of
gems and quantity purchased

4.3 Print pattern 28

4.4 Python program which finds the maximum 29-30


number from num1 to num2 (num2
inclusive) based on the given rules

4.5 To Generate the ticket numbers for specified 30-31


number of passengers travelling in a flight as
per the details mentioned

5 5.1 Python program to categorize all the elements 20/09/24 32


of a given tuple according to their data type

5.2 python program to read a list of strings and 33


count the number of characters in each string

5.3 Function to find the medical speciality 33-35


visited by the maximum number of patients

5.4 Python function, find_correct() which 35-36


accepts a dictionary and returns a list as per
the given mentioned below

5.5 Create a character translator (that works 37-38


similar to the Unix tr command).

6 6.1 Write a python program to compute the area 27/09/24 39-40


of circle, square, and rectangle by using
module.
6.2 Write a python program to calculate the 40-41
frequency of vowels and consonants in file.

6.3 Write a python program to swap the first and 41-42


second half of the input file content.

6.4 Write a program to copy lines which start 42-43


with a lowercase letter and ignore the lines
which start from with an uppercase letter

6.5 Create a Mad Libs program that reads in text 43-45


files and lets the user add their own text
anywhere the word adjective, noun, adverb,
or verb appears in the text file.
7 7.1 Write a Python program to implement the 18/10/24 46-47
class with its attributes and methods for
TechWorld, a technology training center,
wants to allocate courses for instructors.

7.2 Write a Python program to calculate the bill 47-49


amount to be paid by patients visiting the
hospital.

7.3 Write a python program for an apparel shop 49-52


wants to manage the items which it sells

7.4 Write a program to implement the concept of 52-53


multiple inheritance.

8 8.1 Install SQL and verify its installation by 25/10/24 54


creating a test database.

8.2 Create a table Employee in test 54-55

8.3 Insert values into the Employee table by 55-56


adding multiple records.

8.4 Access the Employee table data and print all 56-57
its data.
EXPERIMENT 1
AIM(1.1): To install Python and setting up the compiler
INTRODUCTION:
• In First lab session we will see how to install Python.
• This contains some basic functions and syntax of Python.
• Here we give you a very brief overview of Python programming with concepts and functions that
will be used later in lab assignments.

Python is a high-level, interpreted scripting language developed in the late 1980s by Guido van
Rossum at the Centrum Wiskunde & Informatica (CWI), Amsterdum, Netherlands.

Initially published at the alt.sources newsgroup in 1991, the first version 1.0 was released in 1994.

Python is Portable and simple to code. It is widely used in data science. Well suited for coding deep
learning algorithms using NumPy and Tensorflow.

We will be using Jupyter notebook programming environment for writing codes.

DEVICE USED:WINDOWS LAPTOP

INSTALLING PYTHON ON WINDOW

1.Download Python Installer

• Go to the Official Python Website.( https://www.python.org)


• Click on the latest version (e.g., Python 3.12.5).
• Choose the Windows installer (e.g., python-3.12.5-amd64.exe for 64-bit systems).

1
2.Run the Installer
• Double-click the downloaded installer to start the installation process.

3.Customize Installation (Optional)

• Add Python to PATH: Ensure you check the box “Add Python 3.12.5 to PATH” at the bottom
of the installation window.

• Install Now: Click the “Install Now” button for a standard installation or “Customize
installation” to choose specific features and installation location.

4.Verify Installation

• Open Command Prompt (search for cmd in the Start menu).

• Type python --version and press Enter. You should see the Python version number.

• To check pip (Python package installer), type pip --version.

2
5.Setting Up python in Vs Code

• Open VS Code: Launch VS Code after installation.

• Go to Extensions: Click on the Extensions view icon on the Sidebar or press Ctrl+Shift+X.

• Search: In the search bar, type “Python” and look for the extension published by Microsoft.

• Install: Click "Install" on the Python extension by Microsoft.

6. Configure Python Interpreter

• Open Command Palette: Press Ctrl+Shift+P .

• Select Interpreter: Type "Python: Select Interpreter" and select it from the dropdown menu.

• Choose Interpreter: You’ll see a list of available Python interpreters. Choose the one you
installed or the one you wish to use for your project

7. Create and Run a Python File


• Create a New File: Go to File > New File or press Ctrl+N
• Save the File: Save the new file with a .py extension, like hello.py
Example

Result:

3
AIM(1.2): To Explore basic python functions
[1.] INPUT FUNCTION
• You can use an the input function, just as you might have used 'scanf' in C.
• When the input function is called, the program flow will be stopped until you give an input
and end it using the return key.
• The text of the optional parameter, i.e., the prompt, will be printed on the screen.
• The input of the user will be interpreted. If you input an integer value, the input function will
return this integer value. If you input a list, the function will return the list.

Example:
name = input("What's your name? ")
print("Welcome " + name + " to the training program on Artificial Intelligence and machine
learning!")
city = input("Where are you from ?")
print("Nice to know that you come from " + city + "!")

Result:

[2.] MULTI VARIABLE ASSIGNMENT


Example:
a, b, c, d = 1, 5, 2, "Deep Learning and Applications"

print(a,b,c,d)

Result:

[3.] SWAPPING OF TWO VARIABLES


Example:
value1 =90 ; value2 =34
print(value1,'-----',value2)
value1,value2 = value2,value1
print(value1,'-----',value2)
Result:

4
[4.] IF...ELIF...ELSE STATEMENTS
An if-else statement has the following syntax.
Syntax
if expression:
> statement(s)
else:
> statement(s)

Example:
num = int(input("number"))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

Result:

[5.] THE LOOP WORK AS FOLLOWS


A. i.)For Loop ii).Using Range
Example: Example:
for number in [1,10,20,30,40,50]: for i in range(1,10):
print(number) print(i)
Result:

Result:

5
B.While Loop
Example:
value = 2
while value<7:
print(value)
value+=1
Result:

[6.] LIST IN PYTHON


Python offers a range of compound datatypes often referred to as sequences.
List is one of the most frequently used datatypes used in Python.
• A list is created by placing all the items (elements) inside a square bracket [ ], separated by
commas.
• It can have any number of items and they may be of different types (integer, float, string etc.).
Accessing the elements of the list
You can use the index operator [ ] to access an item in a list. Index starts from 0. So, a list having 5
elements will have indices ranging from 0 to 4.
Example:
# empty list
my_list = []
print(my_list)
# list of integers
my_list = [1, 2, 3]
print(my_list)
# list with mixed datatypes
my_list = [1, "Deep Learning and Applications", 2.5]
print(my_list)

Results:

6
(ii) Example:
# Deleting and Entry from the list

list1 = ['Deep Learning', 'Applications', 11, 15]


print (list1)
del list1[2]
print ("After deleting value at index 2 : ", list1)
Result:

(iii) Example:
# Merging two lists

a1 = [1,2,3,4,5,9]
a2 = [2,4,512,1,3]
a3 = ['Aditya', 'Ronit', 'Vikrant']
print(a1+a2+a3)
Result:

[7.] TUPLE IN PYTHON


A Tuple is a collection of Python objects separated by commas. A tuple is somewhat similar to a list
in terms of indexing, nested objects and repetition. But it may be noted that a tuple is immutable
unlike lists which are mutable.
Example:
tuple1 = (2,2.3, 'E&ICT Academy')
print(tuple1)
Results:

7
AIM(1.3): To Construct a Calculator using Python which performs basic mathematical operations
CODE:
def add(x, y):
return x + y

def subtract(x, y):


return x - y

def multiply(x, y):


return x * y

def divide(x, y):


if y == 0:
return "Error!"
else:
return x / y

def power(x, y):


return x ** y

def modulus(x, y):


return x % y

print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Power")
print("6. Modulus")

while True:
choice = input("Enter choice (1/2/3/4/5/6): ")

if choice in ('1', '2', '3', '4', '5', '6'):


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
print("Result:", add(num1, num2))
elif choice == '2':
print("Result:", subtract(num1, num2))
elif choice == '3':
print("Result:", multiply(num1, num2))
elif choice == '4':
print("Result:", divide(num1, num2))
elif choice == '5':
print("Result:", power(num1, num2))
elif choice == '6':
print("Result:", modulus(num1, num2))

break
else:
print("Invalid input. Please enter a valid operation number.")

8
OUTPUT:

9
EXPERIMENT 2
AIM(2.1): WAP to find the number of days in a month.
PROGRAM:
def get_days_in_month(month, year):
# List of month names
month_names = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
]

# Handle month input


if isinstance(month, str):
month = month.capitalize()
if month in month_names:
month_number = month_names.index(month) + 1
else:
return None, "Invalid month name. Please enter a valid month name."
else:
# Assume month is an integer
if 1 <= month <= 12:
month_number = month
else:
return None, "Invalid month number. Please enter a number between 1 and 12."

# Get the month name based on the month number


month_name = month_names[month_number - 1]

# Calculate the number of days


if month_number == 2:
# Leap year condition
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
days = 29
else:
days = 28
elif month_number in [1, 3, 5, 7, 8, 10, 12]:
days = 31
else:
days = 30

return month_name, days

def main():
print("Choose an option to enter the month:")
print("1. Enter the month as a number (1-12)")
print("2. Enter the month as a string (e.g., 'January')")

10
choice = input("Enter your choice (1 or 2): ")

if choice == '1':
# Enter month as a number
try:
month = int(input("Enter the month number (1-12): "))
year = int(input("Enter the year: "))
except ValueError:
print("Invalid input. Please enter valid numbers.")
return

elif choice == '2':


# Enter month as a string
month = input("Enter the month name (e.g., 'January'): ").strip()
try:
year = int(input("Enter the year: "))
except ValueError:
print("Invalid input. Please enter a valid number for the year.")
return

else:
print("Invalid choice. Please select 1 or 2.")
return

month_name, days = get_days_in_month(month, year)

if month_name is None:
print(days) # Print the error message
else:
print(f"{month_name} {year} has {days} days")

# Run the main function


main()

OUTPUT1:

11
OUTPUT2:

AIM(2.2):WAP to display the pattern of numbers given as follows:


1
12
123
1234
123
12
1
PROGRAM:
m=4
# Print the increasing part of the pattern
for i in range(1, m + 1):
for j in range(1, i + 1):
print(j, end=' ')
print() # Move to the next line

# Print the decreasing part of the pattern


for i in range(m - 1, 0, -1):
for j in range(1, i + 1):
print(j, end=' ')
print()

OUTPUT:

12
AIM(2.3):WAP using while loop, which prints the sum of every fifth number from 0
to 500 (including both 0 and 500)
PROGRAM:
# Initialize variables
start = 0
end = 500
step = 5
sum_of_numbers = 0

# Initialize the loop variable


current_number = start
index=0
# Use a while loop to iterate through every fifth number
while current_number <= end:
sum_of_numbers += current_number
current_number += step
index=index+1
print(f"EVERY 5th {index} elements:",sum_of_numbers)

# Print the result


print("The sum of every fifth number from 0 to 500 is:", sum_of_numbers)

OUTPUT:

13
AIM(2.4): Write a python program to display all the common characters between two
strings. Return -1 if there are no matching characters.
PROGRAM:
def common_characters(str1, str2):
# Convert both strings to lowercase
str1 = str1.lower()
str2 = str2.lower()

# Convert both strings to sets to get unique characters


set1 = set(str1)
set2 = set(str2)

# Find the intersection of both sets


common_chars = set1.intersection(set2)

# Check if there are common characters


if common_chars:
# Convert the set to a sorted list
sorted_chars = sorted(common_chars)

# Build the result string manually


result = ""
for char in sorted_chars:
result += char

return result
else:
return -1

# Example usage
string1 = input("Enter the 1st string: ")
string2 = input("Enter the 2nd string: ")

result = common_characters(string1, string2)


if result != -1:
print(f"Common characters: {result}")
else:
print("No common characters.")

OUTPUT:

14
AIM(2.5): Given two lists, both having String elements, write a python program using
python lists to create a new string as per the rule given below:
The first element in list1 should be merged with last element in list2, second element in list1
should be merged with second last element in list2 and so on. If an element in list1/list2 is
None, then the corresponding element in the other list should be kept as it is in the merged
list.

Sample Input Expected Output

list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']


“An apple a day keeps the doctor away”
list2=['y','tor','e','eps','ay',None,'le','n']

PROGRAM:
def merge_lists(list1, list2):
# Initialize an empty list to store the merged result
merged_list = []

# Calculate the length of the lists


len1 = len(list1)
len2 = len(list2)

# Iterate over the range of the larger length of the two lists
for i in range(max(len1, len2)):
# For list1, use element if it's available
if i < len1:
l1_elem = list1[i]
else:
l1_elem = None

# For list2, use element from the end if it's available


if i < len2:
l2_elem = list2[-(i + 1)]
else:
l2_elem = None

# Merge elements according to the rules


if l1_elem is None:
merged_list.append(l2_elem if l2_elem is not None else '')
elif l2_elem is None:
merged_list.append(l1_elem if l1_elem is not None else '')
else:
merged_list.append(l1_elem + l2_elem)

# Build the result string manually


result = ""
first_element = True

15
for item in merged_list:
if item: # Add non-empty items
if not first_element:
result += " " # Add space before the item if it's not the first one
result += item
first_element = False

return result

# Sample input
list1 = ['A', 'app', 'a', 'd', 'ke', 'th', 'doc', 'awa']
list2 = ['y', 'tor', 'e', 'eps', 'ay', None, 'le', 'n']

# Generate and print the merged string


result = merge_lists(list1, list2)
print(result)

OUTPUT:

16
EXPERIMENT 3
AIM(3.1): Given a string containing uppercase characters (A-Z), compress the string using
Run Length encoding. Repetition of character has to be replaced by storing the length of that
run.Write a python function which performs the run length encoding for a given String and
returns the run length encoded String. Provide different String values and test your program.

Sample Input Expected Output

AAAABBBBCCCCCCCC 4A4B8C

AABCCA 2A1B2C1A

PROGRAM:
def run_length_encoding(s):
if not s:
return ""

encoded_str = []
count = 1

for i in range(1, len(s)):


if s[i] == s[i - 1]:
count += 1
else:
encoded_str.append(f"{count}{s[i - 1]}")
count = 1

encoded_str.append(f"{count}{s[-1]}")

# Convert list to string manually


result = ""
for part in encoded_str:
result += part

return result

def get_user_input():
s = input("Enter a string (in capital letters) to encode: ")
return s

if __name__ == "__main__":
user_input = get_user_input()
encoded_string = run_length_encoding(user_input)
print(f"Encoded string: {encoded_string}")

17
OUTPUT:

AIM(3.2): Write a python function, find_pairs_of_numbers() which accepts a list of


positive integers with no repetitions and returns count of pairs of numbers in the list
that adds up to n. The function should return 0, if no such pairs are found in the list.

Sample Input Expected Output

[1, 2, 7, 4, 5, 6, 0, 3], 6 3

[3, 4, 1, 8, 5, 9, 0, 6], 9 4

PROGRAM:
def find_pairs_of_numbers(nums, n):
seen = set()
pairs = set()

for num in nums:


complement = n - num

if complement in seen:
pair = tuple(sorted((num, complement)))
pairs.add(pair)

seen.add(num)

return len(pairs)

def get_user_input():
numbers_input = input("Enter a list of uniue numbers separated by spaces: ")
nums = list(map(int, numbers_input.split()))

target_sum = int(input("Enter the target sum: "))

return nums, target_sum


if __name__ == "__main__":
nums, target_sum = get_user_input()
result = find_pairs_of_numbers(nums, target_sum)
print(f"Number of unique pairs that sum to {target_sum}: {result}")

18
OUTPUT:

AIM(3.3): A teacher is in the process of generating few reports based on the marks scored
by the students of her class in a project based assessment. Assume that the marks of her 10
students are available in a tuple. The marks are out of 25. Write a python program to
implement the following functions:

• find_more_than_average(): Find and return the percentage of students who have scored
more than the average mark of the class.
• generate_frequency(): Find how many students have scored the same marks. For
example, how many have scored 0, how many have scored 1, how many have scored
3….how many have scored 25. The result should be populated in a list and returned.
• sort_marks(): Sort the marks in the increasing order from 0 to 25. The sorted values
should be populated in a list and returned.

PROGRAM:
def find_more_than_average(marks):
average = sum(marks) / len(marks)
count_above_average = sum(1 for mark in marks if mark > average)

# Calculate the percentage of students who scored more than the average
percentage_above_average = (count_above_average / len(marks)) * 100

return percentage_above_average

def generate_frequency(marks):
# Initialize a frequency list with 26 elements (0-25)
frequency = [0] * 26

for mark in marks:


frequency[mark] += 1

# Create a list of tuples with mark and its frequency


frequency_with_marks = [(i, frequency[i]) for i in range(len(frequency))]

return frequency_with_marks

def sort_marks(marks):
# Sort the marks in ascending order

19
sorted_marks = sorted(marks)

return sorted_marks

def main():

while True:
try:
# Input the marks as a comma-separated string
input_marks = input("Enter the marks of 10 students (comma-separated,from 25, e.g., ): ")

# Convert the input string to a tuple of integers


marks = tuple(map(int, input_marks.split(',')))

# Ensure there are exactly 10 marks


if len(marks) != 10:
print("Please enter exactly 10 marks.")
continue

# Check if all marks are within the valid range (0 to 25)


if any(mark < 0 or mark > 25 for mark in marks):
print("Marks should be between 0 and 25.")
continue

# Calculate results
percentage_above_average = find_more_than_average(marks)
frequency_with_marks = generate_frequency(marks)
sorted_marks = sort_marks(marks)

# Display results
print(f"Percentage of students who scored more than the average:
{percentage_above_average:.2f}%")

print("Frequency of marks (index and frequency):")


for mark, freq in frequency_with_marks:
if freq > 0: # Print only marks that have non-zero frequencies
print(f"Mark {mark}: {freq} student(s)")
print(f"Sorted marks: {sorted_marks}")

break
except ValueError:
print("Invalid input. Please enter only integers separated by commas.")

main()

20
OUTPUT:

AIM(3.4): Write a python function, create_largest_number(), which accepts a list of


numbers and returns the largest number possible by concatenating the list of numbers.
Note: Assume that all the numbers are two digit numbers

Sample Input Expected Output

23,34,55 553423

PROGRAM:
def compare(x, y):
if x + y > y + x:
return -1
elif x + y < y + x:
return 1
else:
return 0

def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if compare(arr[j], arr[j+1]) > 0:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr

def create_largest_number(numbers):
numbers_str = list(map(str, numbers))
sorted_numbers = bubble_sort(numbers_str)
largest_number = ''.join(sorted_numbers)

21
return str(int(largest_number))

def get_user_input():
input_str = input("Enter 2 digit numbers separated by spaces: ")
numbers = list(map(int, input_str.split()))
return numbers

if __name__ == "__main__":
numbers = get_user_input()
print(create_largest_number(numbers))

OUTPUT:

AIM(3.5): Consider sample data as follows: sample_data=range(1,11). Create two


functions: odd() and even(). The function even() returns a list of all the even numbers from
sample_data. The function odd() returns a list of all the odd numbers from sample_data.
Create a function sum_of_numbers() which will accept the sample data and/or a function. If a
function is not passed, the sum_of_numbers() should return the sum of all the numbers from
sample_data. If a function is passed, the sum_of_numbers() should return the sum of
numbers returned from the function passed.

PROGRAM:
sample_data = range(1, 11)

def even():

return [num for num in sample_data if num % 2 == 0]

def odd():

return [num for num in sample_data if num % 2 != 0]

def sum_of_numbers(func=None):

if func:
numbers = func()
else:

22
numbers = sample_data

return sum(numbers)

print("Even numbers:", even())


print("Odd numbers:", odd())
print("Sum of all numbers:", sum_of_numbers())
print("Sum of even numbers:", sum_of_numbers(even))
print("Sum of odd numbers:", sum_of_numbers(odd))

OUTPUT:

AIM(3.6): Write a python function, check_anagram() which accepts two strings and returns
True, if one string is an anagram of another string. Otherwise returns False.
The two strings are considered to be an anagram if they contain repeating characters but none
of the characters repeat at the same position. The length of the strings should be the same.
Note: Perform case insensitive comparison wherever applicable.

Sample Input Expected Output

eat, tea True

backward,drawback False
(Reason: character
'a' repeats at position
6, not an anagram)

Reductions,discounter True

About, table False

23
PROGRAM:
def check_anagram(str1, str2):
str1 = str1.lower()
str2 = str2.lower()

if len(str1) != len(str2):
return False

for i in range(len(str1)):
if str1[i] == str2[i]:
return False

return sorted(str1) == sorted(str2)

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

return str1, str2

if __name__ == "__main__":
str1, str2 = get_user_input()

result = check_anagram(str1, str2)

if result:
print("The strings are anagrams.")
else:
print("The strings are not anagrams.")

OUTPUT:

24
EXPERIMENT 4
AIM(4.1): Say you have a list value like this: spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list value as an argument and returns a string with all the items
separated by a comma and a space, with and inserted before the last item. For example,
passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'.
But your function should be able to work with any list value passed to it

PROGRAM:
def format_list(items):
# Handle empty list
if not items:
return ""

# If there's only one item, return it as is


if len(items) == 1:
return items[0]

# Initialize an empty string to build the result


result = ""
# Add all items except the last one with a comma and space
for i in range(len(items) - 1):
result += items[i] + ", "

# Add "and" before the last item


result += "and " + items[-1]

return result
def get_user_input():
# Prompt the user to enter items separated by commas
user_input = input("Enter items separated by commas: ")

# Split the input string into a list of items, stripping any extra spaces
items = [item.strip() for item in user_input.split(',')]

return items
spam = get_user_input()
formatted_string = format_list(spam)
print(formatted_string)

OUTPUT:

25
AIM(4.2): ARS Gems Store sells different varieties of gems to its customers. Write a
Python program to calculate the bill amount to be paid by a customer based on the list of
gems and quantity purchased. Any purchase with a total bill amount above Rs.30000 is
entitled for 5% discount. If any gem required by the customer is not available in the store,
then consider total bill amount to be -1. Assume that quantity required by the customer for
any gem will always be greater than 0. Perform case-sensitive comparison wherever
applicable.

PROGARM:
gem_prices = {
'Ruby': 15000,
'Emerald': 20000,
'Diamond': 50000,
'Sapphire': 10000,
'Topaz': 5000
}

def calculate_bill(purchases):
total_amount = 0

for gem, quantity in purchases.items():


if gem not in gem_prices:
return -1 # Gem not available in the store

total_amount += gem_prices[gem] * quantity

# Apply discount if total amount exceeds Rs. 30000


if total_amount > 30000:
total_amount *= 0.95 # Apply 5% discount

return total_amount

def get_customer_purchases():
purchases = {}
print("Enter the gem purchases in the format 'gem_name quantity'. Type 'done' when finished.")

while True:
entry = input("Enter gem and quantity: ").strip() #Strip remove spaces from string
if entry.lower() == 'done':
break

# Split input into gem name and quantity


parts = entry.split() #Split where spaces into list
if len(parts) != 2:
print("Invalid input format. Please enter in the format 'gem_name quantity'.")

26
continue

gem = parts[0]
quantity_str = parts[1]

# Validate quantity
if quantity_str.isdigit():
quantity = int(quantity_str)
if quantity > 0:
purchases[gem] = quantity
else:
print("Quantity must be greater than 0.")
else:
print("Quantity must be a positive integer.")

return purchases

# Main program
if __name__ == "__main__":
customer_purchases = get_customer_purchases()
bill_amount = calculate_bill(customer_purchases)

if bill_amount == -1:
print("One or more gems are not available in the store.")
else:
print(f"Total bill amount: Rs. {bill_amount:.2f}")

OUTPUT:

27
AIM(4.3): Say you have a list of lists where each value in the inner lists is a one-character
string, like this:
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]

PROGRAM:
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]

# Determine the number of rows and columns in the grid


num_rows = len(grid)
num_cols = len(grid[0]) if num_rows > 0 else 0 ##based on 1st row

# Print the grid transposed


for y in range(num_cols):
for x in range(num_rows):
print(grid[x][y], end='') # Print character without newline
print() # Print newline after each column

OUTPUT:

28
AIM(4.4): Write a python program which finds the maximum number from num1 to num2
(num2 inclusive) based on the following rules.
1. Always num1 should be less than num2
2. Consider each number from num1 to num2 (num2 inclusive). Populate the number
into a list, if the below conditions are satisfied
a. Sum of the digits of the number is a multiple of 3
b. Number has only two digits
c. Number is a multiple of 5
3. Display the maximum element from the list
4.In case of any invalid data or if the list is empty, display -1.

PROGRAM:
def sum_of_digits(n):
return sum(int(digit) for digit in str(n))

def is_valid_number(num):
return (
10 <= num <= 99 and # Check if the number has exactly two digits
num % 5 == 0 and # Check if the number is a multiple of 5
sum_of_digits(num) % 3 == 0 # Check if the sum of digits is a multiple of 3
)

def find_max_in_range(num1, num2):

if num1 >= num2:


return -1

# Generate list of valid numbers


valid_numbers = [num for num in range(num1, num2 + 1) if is_valid_number(num)]

# Return maximum number if list is not empty


if valid_numbers:
return max(valid_numbers)
else:
return -1

# Example usage
num1 = int(input("Enter num1: "))
num2 = int(input("Enter num2: "))
result = find_max_in_range(num1, num2)
print(result)

29
OUTPUT:

AIM(4.5): Write a python program to generate the ticket numbers for specified number of
passengers travelling in a flight as per the details mentioned below:
The ticket number should be generated as airline:src:dest:number
where
1. Consider AI as the value for airline
2. src and dest should be the first three characters of the source and destination cities.
3. number should be auto-generated starting from 101
4. The program should return the list of ticket numbers of last five passengers.
Note: If passenger count is less than 5, return the list of all generated ticket numbers

PROGRAM:
def generate_ticket_numbers(src_city, dest_city, num_passengers):
airline_code = "AI"
src_code = src_city[:3].upper()
dest_code = dest_city[:3].upper()

ticket_numbers = []

for i in range(101, 101 + num_passengers):


ticket_number = f"{airline_code}:{src_code}:{dest_code}:{i}"
ticket_numbers.append(ticket_number)

# Return the last five ticket numbers or all if fewer than five
return ticket_numbers[-5:] if num_passengers >= 5 else ticket_numbers # -n ...... -2 -1

# Example usage
src_city = input("Enter source city: ")
dest_city = input("Enter destination city: ")
num_passengers = int(input("Enter number of passengers: "))
last_five_tickets = generate_ticket_numbers(src_city, dest_city, num_passengers)
for ticket in last_five_tickets:
print(ticket)

30
OUTPUT:

31
EXPERIMENT 5
AIM(5.1): Write a Python program to categorize all the elements of a given tuple according
to their data type. Store the results of each category into a new sub-tuple. Display the sorted
order of each sub-tuple.
Program:
def categorize_and_sort_tuple(input_tuple):
categorized_elements = {
'int': [],
'float': [],
'str': [],
'bool': [],
'list': [],
'tuple': [],
'dict': [],
'set': [],
'NoneType': []
}
for element in input_tuple:

element_type = type(element).__name__##tuple return<class int> ,name return int


if element_type in categorized_elements:
categorized_elements[element_type].append(element)
else:
categorized_elements['NoneType'].append(element)

# Sort and convert each list to a tuple


sorted_tuples = {key: tuple(sorted(value, key=lambda x: str(x))) for key, value in
categorized_elements.items()}

return sorted_tuples

input_tuple = (5, 2.5, 'hello', True, [1, 2], (1, 2), {'key': 'value'}, {1, 2}, None, 3.14, 'world')

sorted_result = categorize_and_sort_tuple(input_tuple)
for category, items in sorted_result.items():
print(f"{category.capitalize()} elements: {items}")

Output:

32
AIM(5.2): Write a python program to read a list of strings and count the number of
characters in each string. Store the output in the dictionary
Program:
def count_characters(strings_list):
count_dict = {}

for string in strings_list:


char_count = 0

for y in string:
char_count += 1

count_dict[string] = char_count
return count_dict

strings_list = ["apple", "banana", "cherry", "date"]


count_result = count_characters(strings_list)

print("Character counts for each string:")


for string, count in count_result.items():
print(f"'{string}': {count} characters")

Output:

AIM(5.3): Care hospital wants to know the medical speciality visited by the maximum
number of patients. Assume that the patient id of the patient along with the medical speciality
visited by the patient is stored in a list. The details of the medical specialities are stored in a
dictionary as follows:
{
"P":"Pediatrics",
"O":"Orthopedics",
"E":"ENT
}
Write a function to find the medical speciality visited by the maximum number of patients
and return the name of the speciality.

33
Note:
1. Assume that there is always only one medical speciality which is visited by maximum
number of patients.
2. Perform case sensitive string comparison wherever necessary.
Expected
Sample Input
Output
[101,P,102,O,302,P,305,P] Pediatrics

[101,O,102,O,302,P,305,E,401,O,656,O] Orthopedics
[101,O,102,E,302,P,305,P,401,E,656,O,987,E] ENT

Program:
def most_visited_speciality(patient_visits):

specialty_map = {
"P": "Pediatrics",
"O": "Orthopedics",
"E": "ENT"
}
# Initialize a dictionary to count occurrences of each specialty code
specialty_count = {
"P": 0,
"O": 0,
"E": 0
}
# Count the number of patients visiting each specialty
for i in range(1, len(patient_visits), 2): # Start from index 1 and step by 2
specialty_code = patient_visits[i]
if specialty_code in specialty_count:
specialty_count[specialty_code] += 1
# Find the specialty with the maximum number of visits
max_specialty_code = max(specialty_count, key=specialty_count.get)
return specialty_map[max_specialty_code]

def main():

input_string = input("Enter the list of patient visits (e.g., 101,P,102,O,302,P,305,P): ")


# Convert input string to a list
patient_visits = input_string.split(',')
# Find the most visited specialty
result = most_visited_speciality(patient_visits)

34
# Print the result
print("The medical specialty visited by the maximum number of patients is:", result)

if __name__ == "__main__":
main()

Output:

AIM(5.4): Write a python function, find_correct() which accepts a dictionary and returns a
list as per the rules mentioned below. The input dictionary will contain correct spelling of a
word as key and the spelling provided by a contestant as the value. The function should
identify the degree of correctness as mentioned below:
CORRECT, if it is an exact match
ALMOST CORRECT, if no more than 2 letters are wrong
WRONG, if more than 2 letters are wrong or if length (correct spelling versus spelling given
by contestant) mismatches.
and return a list containing the number of CORRECT answers, number of ALMOST
CORRECT answers and number of WRONG answers.
Assume that the words contain only uppercase letters and the maximum word length is 10.
Sample Input
{"THEIR": "THEIR", "BUSINESS":
"BISINESS","WINDOWS":"WINDMILL","WERE":"WEAR","SAMPLE":"SAMPLE"}

Expected Output: [2,2,1]

Program:
def find_correct(spelling_dict):
def compare_words(correct, contestant):
if correct == contestant:
return "CORRECT"

35
if len(correct) != len(contestant):
return "WRONG"

# Count the number of differing characters


wrong_count = 0
for i in range(len(correct)):
if correct[i] != contestant[i]:
wrong_count += 1

if wrong_count <= 2:
return "ALMOST CORRECT"
else:
return "WRONG"
# Initialize counts
correct_count = 0
almost_correct_count = 0
wrong_count = 0

for correct, contestant in spelling_dict.items():


result = compare_words(correct, contestant)
if result == "CORRECT":
correct_count += 1
elif result == "ALMOST CORRECT":
almost_correct_count += 1
else:
wrong_count += 1

print(f"Correct: {correct_count}")
print(f"Almost Correct: {almost_correct_count}")
print(f"Wrong: {wrong_count}")

# Return counts as a list


return [correct_count, almost_correct_count, wrong_count]

spelling_dict = {"THEIR": "THEIR", "BUSINESS": "BISINESS", "WINDOWS": "WINDMILL",


"WERE": "WEAR", "SAMPLE": "SAMPLE"}
result = find_correct(spelling_dict)
print(result)

Output:

36
AIM(5.5):
(a) Create a character translator (that works similar to the Unix tr command). This function,
which we will call tr(), takes three strings as arguments: source,
destination, and base strings, and has the following declaration:
def tr(srcstr, dststr, string)
srcstr contains the set of characters you want "translated," dststr contains the set of characters
to translate to, and string is the string to perform the translation on. For example, if srcstr ==
'abc', dststr == 'mno', and string =='abcdef', then tr() would output 'mnodef'. Note that
len(srcstr) ==len(dststr). For this exercise, you can use the chr() and ord() built-in functions,
but they are not necessary to arrive at a solution.

Program:
def tr(srcstr, dststr, string):
# Create a translation map using ord() and chr()
translation_map = {}

for i in range(len(srcstr)):
src_char = srcstr[i]
dst_char = dststr[i]
translation_map[ord(src_char)] = ord(dst_char)

# Translate the string using the map


translated_string = ''
for char in string:
translated_string += chr(translation_map.get(ord(char), ord(char)))
return translated_string

srcstr = 'abc'
dststr = 'mno'
string = 'abcdef'
result = tr(srcstr, dststr, string)
print(result)

Output:

37
(b) Update your solution so that it can process character deletions. Any extra characters in
srcstr which are beyond those which could be mapped to characters in dststr should be
filtered. In other words, these characters are mapped to no characters in dststr, and are thus
filtered from the modified string which is returned. For example, if srcstr == 'abcdef', dststr
== 'mno', and string== 'abcdefghi', then tr() would output 'mnoghi'. Note now thatlen(srcstr)
>= len(dststr).

Program:
def tr(srcstr, dststr, string):
valid_src = srcstr[:len(dststr)]
translation_map = {}

for i in range(len(valid_src)):
translation_map[valid_src[i]] = dststr[i]
result_string = ''
for char in string:
if char in translation_map:
result_string += translation_map[char]
elif char not in srcstr:
result_string += char

return result_string
srcstr = 'abcdef'
dststr = 'mno'
string = 'abcdefghi'
print(tr(srcstr, dststr, string))

Output:

38
EXPERIMENT 6
AIM(6.1):Write a python program to compute the area of circle, square, and rectangle by
using module.
Program:
Shapes.py
PI = 3.14159

def area_circle(radius):
"""Calculate the area of a circle."""
return PI * (radius ** 2)

def area_square(side):
"""Calculate the area of a square."""
return side ** 2

def area_rectangle(length, width):


"""Calculate the area of a rectangle."""
return length * width

Main.py
from shapes import area_circle, area_square, area_rectangle

def main():
while True:
print("\nArea Calculator")
print("Select an option:")
print("1. Calculate the area of a circle")
print("2. Calculate the area of a square")
print("3. Calculate the area of a rectangle")
print("4. Exit")

choice = input("Enter your choice (1-4): ")

if choice == '1':
radius = float(input("Enter the radius of the circle: "))
circle_area = area_circle(radius)
print(f"The area of the circle is: {circle_area:.2f}")

elif choice == '2':


side = float(input("Enter the side length of the square: "))
square_area = area_square(side)
print(f"The area of the square is: {square_area:.2f}")

elif choice == '3':


length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
rectangle_area = area_rectangle(length, width)
print(f"The area of the rectangle is: {rectangle_area:.2f}")

39
elif choice == '4':
print("Exiting the program.")
break

else:
print("Invalid choice. Please select a valid option.")

if __name__ == "__main__":
main()

Output:

AIM(6.2): Write a python program to calculate the frequency of vowels and consonants in
file
Program:
Sample.txt
Hello, world! This is a simple text file for testing.
It includes vowels and consonants.

40
Count.py
def count_vowels_consonants(filename):
vowels = "aeiouAEIOU"
consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"

vowel_count = 0
consonant_count = 0

try:
with open(filename, 'r') as file:
text = file.read()

for char in text:


if char in vowels:
vowel_count += 1
elif char in consonants:
consonant_count += 1

except FileNotFoundError:
print(f"The file '{filename}' does not exist.")
return

print(f"Total Vowels: {vowel_count}")


print(f"Total Consonants: {consonant_count}")

if __name__ == "__main__":
N=input("Enter File name:")
count_vowels_consonants(N)

Output:

AIM(6.3): Write a python program to swap the first and second half of the input file
content.

Program:
Sample.txt

41
Hello, world! This is a simple text file for testing.
It includes vowels and consonants.

Main.py
def swap_file_halves(filename):
try:
with open(filename, 'r') as file:
content = file.read()

midpoint = len(content) // 2

first_half = content[:midpoint]
second_half = content[midpoint:]

swapped_content = second_half + first_half


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

print(f"Swapped content written back to '{filename}'.")

except FileNotFoundError:
print(f"The file '{filename}' does not exist.")
except Exception as e:
print(f"An error occurred: {e}")

if __name__ == "__main__":
N=input("Enter file name:")
swap_file_halves(N)

Output:

Sample.txt
It includes vowels and consonants
Hello, world! This is a simple text file for testing.

AIM(6.4): Write a program to copy lines which start with a lowercase letter only from the
input file Demo.txt and ignore the lines which start from with an uppercase letter. The output
file Demo2.txt should contain only those lines from the file Demo.txt which start with a
lowercase letter.

Program:

42
Demo.txt
This is the first line.
this is the second line.
Another line starts with uppercase.
yet another line starts with lowercase.

Main.py
def copy_lowercase_lines(input_filename, output_filename):
try:
with open(input_filename, 'r') as infile, open(output_filename, 'w') as outfile:
for line in infile:
if line and line[0].islower():
outfile.write(line)

print(f"Lines starting with lowercase letters copied to '{output_filename}'.")

except FileNotFoundError:
print(f"The file '{input_filename}' does not exist.")
except Exception as e:
print(f"An error occurred: {e}")

if __name__ == "__main__":
copy_lowercase_lines('Demo.txt', 'Demo2.txt')

Output:

Demo2.txt
this is the second line.
yet another line starts with lowercase.

AIM(6.5): Create a Mad Libs program that reads in text files and lets the user add their own text
anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a
text file may look like this:
The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was
unaffected by these events.

43
The program would find these occurrences and prompt the user to replace them.
Enter an adjective:
silly
Enter a noun:
chandelier
Enter a verb:
screamed
Enter a noun:
pickup truck

The following text file would then be created:


The silly panda walked to the chandelier and then screamed. A nearby pickup truck was unaffected
by these events.

The results should be printed to the screen.

Program:
def mad_libs():

input_file = "template.txt"
output_file = "output.txt"

with open(input_file, 'r') as file:


text = file.read()

placeholders = {
"ADJECTIVE": "adjective",
"NOUN": "noun",
"ADVERB": "adverb",
"VERB": "verb"
}

for placeholder, prompt in placeholders.items():


while placeholder in text:
user_input = input(f"Enter a {prompt}: ")
text = text.replace(placeholder, user_input, 1) # Replace the first occurrence only

with open(output_file, 'w') as file:


file.write(text)

print("\nHere is your Mad Libs story:\n")

44
print(text)

if __name__ == "__main__":
mad_libs()

Output:

Output.txt
The good panda walked to the Ashish and then action. A nearby Anup was unaffected by these
events.

45
EXPERIMENT 7
AIM(7.1): TechWorld, a technology training center, wants to allocate courses for instructors.
An instructor is identified by name, technology skills, experience and average feedback.
An instructor is allocated a course, if he/she satisfies the below two conditions:
• eligibility criteria:
• if experience is more than 3 years, average feedback should be 4.5 or more
• if experience is 3 years or less, average feedback should be 4 or more
• he/she should posses the technology skill for the course
Write a Python program to implement the class with its attributes and methods.
Note:
1. Consider all instance variables to be private and methods to be public
2. An instructor may have multiple technology skills, so consider instance variable,
technology_skill to be a list
3. check_eligibility(): Return true if eligibility criteria is satisfied by the instructor. Else, return
false
4. allocate_course(technology): Return true if the course which requires the given technology
can be allocated to the instructor. Else, return false
5. Perform case sensitive string comparison
Represent few objects of the class, initialize instance variables using setter methods, invoke
appropriate methods and test your program.

Program:
class Instructor:
def __init__(self, name, technology_skills, experience, average_feedback):
self.__name = name
self.__technology_skills = technology_skills # List of technology skills
self.__experience = experience
self.__average_feedback = average_feedback

def set_name(self, name):


self.__name = name

def set_technology_skills(self, technology_skills):


self.__technology_skills = technology_skills

def set_experience(self, experience):


self.__experience = experience

def set_average_feedback(self, average_feedback):


self.__average_feedback = average_feedback

46
def check_eligibility(self):
if self.__experience > 3:
return self.__average_feedback >= 4.5
else:
return self.__average_feedback >= 4

def allocate_course(self, technology):


if self.check_eligibility() and technology in self.__technology_skills:
return True
else:
return False

instructor1 = Instructor("Alice", ["Python", "Java"], 4, 4.6)


instructor2 = Instructor("Bob", ["JavaScript", "React"], 2, 3.9)
instructor3 = Instructor("Charlie", ["Python", "C++", "Java"], 3, 4.0)

print(f"Instructor 1 eligible? {instructor1.check_eligibility()}")


print(f"Instructor 2 eligible? {instructor2.check_eligibility()}")
print(f"Instructor 3 eligible? {instructor3.check_eligibility()}")

print(f"Instructor 1 allocated for 'Python'? {instructor1.allocate_course('Python')}")


print(f"Instructor 2 allocated for 'Java'? {instructor2.allocate_course('Java')}")
print(f"Instructor 3 allocated for 'C++'? {instructor3.allocate_course('C++')}")
print(f"Instructor 3 allocated for 'React'? {instructor3.allocate_course('React')}")

Output:

AIM(7.2): Care hospital wants to calculate the bill amount to be paid by patients visiting the
hospital. Bill amount includes consultation fees and price of medicines purchased from their
pharmacy.
Write a Python program to implement the class diagram given below.

47
Method description:
calculate_bill_amount(consultation_fees, quantity_list, price_list): Accept consultation_fees,
quantity_list (quantities of medicines purchased) and price_list (price per quantity of medicines
purchased)
a. Calculate total bill amount to be paid by the patient. Bill amount includes consultation fees
and price of medicines
b. Initialize attribute, bill_amount with the total bill amount
Note: quantity_list and price_list have one-to-one correspondence. Quantity and price per quantity of
1st medicine purchased by the patient is present at 0th index of both lists, 2nd medicine is present at
1st index and so on.

For testing:
• Create objects of Bill class
• Invoke calculate_bill_amount(consultation_fees, quantity_list, price_list) method on Bill
object by passing consultation fees, quantity list and price list
• Display bill id, patient name and bill amount

Program:
class Bill:
def __init__(self, bill_id, patient_name):
self.__bill_id = bill_id
self.__patient_name = patient_name
self.__bill_amount = 0.0

def set_bill_id(self, bill_id):


self.__bill_id = bill_id

def set_patient_name(self, patient_name):


self.__patient_name = patient_name

def get_bill_id(self):
return self.__bill_id

def get_patient_name(self):
return self.__patient_name

def get_bill_amount(self):
return self.__bill_amount

def calculate_bill_amount(self, consultation_fees, quantity_list, price_list):

total_medicine_cost = sum([quantity_list[i] * price_list[i] for i in range(len(quantity_list))])

48
self.__bill_amount = consultation_fees + total_medicine_cost

patient1 = Bill(101, "John Doe")


patient2 = Bill(102, "Jane Smith")

patient1.calculate_bill_amount(300, [2, 1, 3], [50, 100, 30])

patient2.calculate_bill_amount(250, [1, 2], [100, 40])

print(f"Bill ID: {patient1.get_bill_id()}, Patient Name: {patient1.get_patient_name()}, Bill


Amount: {patient1.get_bill_amount()}")
print(f"Bill ID: {patient2.get_bill_id()}, Patient Name: {patient2.get_patient_name()}, Bill
Amount: {patient2.get_bill_amount()}")

Output:

AIM(7.3): An apparel shop wants to manage the items which it sells. Write a python program to
implement the class diagram given below.

Class Description:
Apparel class:

49
1. Initialize static variable counter to 100
2. In the constructor, auto-generate item_id starting from 101 prefixed by "C" for cotton
apparels and "S" for silk apparels. Example – C101, S102, S103, C104 etc.
3. calculate_price(): Add 5% service tax on the price of the apparel and update attribute, price
with the new value
Cotton class:
1. While invoking parent constructor from child constructor, pass "Cotton" as item_type
2. calculate_price(): Update attribute, price of Apparel class based on rules given below
a. Add service tax on price by invoking appropriate method of Apparel class
b. Apply discount on price
c. Add 5% VAT on final price
Silk class:
1. While invoking parent constructor from child constructor, pass "Silk" as item_type
2. calculate_price(): Update attribute, price of Apparel class based on rules given below
a. Add service tax on price by invoking appropriate method of Apparel class
b. Identify points earned based on rules given below:
Silk apparels with price more than Rs. 10000, earn 10 points and anything less than or equal to that
earn 3 points
c. Initialize attribute, points with the identified points
d. Add 10% VAT on price
Note: Perform case sensitive string comparison

For testing:
• Create objects of Cotton class and Silk class
• Invoke calculate_price() on Cotton objects and Silk objects
• Display their details

Program:
class Apparel:

counter = 100 # Static variable

def __init__(self, item_type, price):


Apparel.counter += 1

self.__item_id = (item_type[0] + str(Apparel.counter))


self.__item_type = item_type
self.__price = price

50
def get_item_id(self):
return self.__item_id

def get_item_type(self):
return self.__item_type

def get_price(self):
return self.__price

def set_price(self, price):


self.__price = price

# Method to calculate price with a 5% service tax


def calculate_price(self):
self.__price = self.__price + (0.05 * self.__price)

class Cotton(Apparel):
def __init__(self, price):
Apparel.__init__(self, "Cotton", price)

def calculate_price(self):

Apparel.calculate_price(self)

discount = 0.05 * self.get_price()


discounted_price = self.get_price() - discount

vat = 0.05 * discounted_price


final_price = discounted_price + vat

# Update the price with the final value


self.set_price(final_price)

class Silk(Apparel):
def __init__(self, price):
super().__init__("Silk", price)
self.__points = 0
def calculate_price(self):
super().calculate_price()

if self.get_price() > 10000:


self.__points = 10
else:
self.__points = 3

vat = 0.10 * self.get_price()


final_price = self.get_price() + vat

self.set_price(final_price)

def get_points(self):

51
return self.__points

cotton_item = Cotton(2000)
cotton_item.calculate_price()

silk_item = Silk(12000)
silk_item.calculate_price()

print(f"Cotton Item ID: {cotton_item.get_item_id()}")


print(f"Type: {cotton_item.get_item_type()}")
print(f"Final Price: {cotton_item.get_price()}")

print(f"Silk Item ID: {silk_item.get_item_id()}")


print(f"Type: {silk_item.get_item_type()}")
print(f"Final Price: {silk_item.get_price()}")
print(f"Points Earned: {silk_item.get_points()}")

Output:

AIM(7.4):Write a program to implement the concept of multiple inheritance.


a. Create the parent class Shape. Initialise the constructor with Shape.
b. Create another class named Rectangle which inherits the properties of the parent class Shape.
Define the attributes length and breadth in the Rectangle class. Initialise the length and
breadth inside the constructor of the Rectangle class. Also call the constructor of the parent
class to initialise the color of the Rectangle. Define the method calc_area() to return the area
of the rectangle.

52
c. Create another class named Traingle which inherits the properties of the parent class Shape.
Define the attributes base and height on the Traingle class. Initialize the base and height
inside the constructor of the Traingle class. Also call the constructor of the parent class to
initialize the color of the Traingle. Define the method calc_area() to return the area of the
Traingle.
d. Finally, create the instance of the Rectangle and Traingle classes to return the area of the
Rectangle and Traingle.
Program:
class Shape:
def __init__(self, color):
self.color = color

def get_color(self):
return self.color

class Rectangle(Shape):
def __init__(self, length, breadth, color):

super().__init__(color)
self.length = length
self.breadth = breadth

def calc_area(self):
return self.length * self.breadth

class Triangle(Shape):
def __init__(self, base, height, color):
super().__init__(color)

self.base = base
self.height = height

def calc_area(self):
return 0.5 * self.base * self.height

rectangle = Rectangle(5, 3, "Blue")

print(f"Rectangle Color: {rectangle.get_color()}")


print(f"Rectangle Area: {rectangle.calc_area()}")

triangle = Triangle(6, 4, "Red")

print(f"Triangle Color: {triangle.get_color()}")


print(f"Triangle Area: {triangle.calc_area()}")

Output:

53
EXPERIMENT 8
AIM(8.1): Install SQL and verify its installation by creating any test database
Program:
import pymysql
mydb=pymysql.connect(
host="localhost",
user="root",
password="Ashish@123")

mycursor=mydb.cursor()
mycursor.execute("CREATE DATABASE Ashishdatabase ")
print(“Database created successfully”)

Output:

AIM(8.2): Create a table Employee in test with the following Fields:


First_Name CHAR(20) NOT NULL
Last_Name CHAR(20)
Age INT
Gender CHAR(1)
Department CHAR(20)
Income FLOAT

Program:
import pymysql

mydb = pymysql.connect(
host="localhost",
user="root",
password="Ashish@123",
database="ashishdatabase"
)

mycursor = mydb.cursor()

#If table exits drop it otherwise value getting add 2 times


Drop_table_query="""
DROP TABLE Employee

54
"""
mycursor.execute(Drop_table_query)

create_table_query = """
CREATE TABLE Employee (
First_Name CHAR(20) NOT NULL,
Last_Name CHAR(20),
Age INT,
Gender CHAR(1),
Department CHAR(20),
Roll INT
);
"""

mycursor.execute(create_table_query)

mydb.commit()

mydb.close()

print("Employee table created successfully.")

Output:

AIM(8.3): Insert values into the Employee table by adding multiple records.
Program:
import pymysql

mydb = pymysql.connect(
host="localhost",
user="root",
password="Ashish@123",
database="ashishdatabase"
)

mycursor = mydb.cursor()

insert_query = """
INSERT INTO StudentRecord (First_Name, Last_Name, Age, Gender, Department, Roll)

55
VALUES
('Ashish', 'Mahajan', 19, 'M', 'UIET', 28),
('Anup', 'kumar', 20, 'M', 'UIET', 24);
"""

mycursor.execute(insert_query)

mydb.commit()

mydb.close()

print("Multiple records inserted successfully.")

Output:

AIM(8.4): Access the Employee table data and print all its data.
Program:
import pymysql

mydb = pymysql.connect(
host="localhost",
user="root",
password="Ashish@123",
database="ashishdatabase"
)

mycursor = mydb.cursor()

select_query = "SELECT * FROM StudentRecord"

mycursor.execute(select_query)

rows = mycursor.fetchall()

print("StudentRecord Table:")
for row in rows:

56
print(row)

mydb.close()

Output:

57

You might also like