Python Uiet (1) 3
Python Uiet (1) 3
( PEIT501c )
PRACTICAL FILE
3 3.1 Perform run length coding on string and return 23/08/24 17-18
the ecnoded string.
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.
1
2.Run the Installer
• Double-click the downloaded installer to start the installation process.
• 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
• Type python --version and press Enter. You should see the Python version number.
2
5.Setting Up python in Vs Code
• 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.
• 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
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:
print(a,b,c,d)
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:
Result:
5
B.While Loop
Example:
value = 2
while value<7:
print(value)
value+=1
Result:
Results:
6
(ii) Example:
# Deleting and Entry from the list
(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
AIM(1.3): To Construct a Calculator using Python which performs basic mathematical operations
CODE:
def add(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 == '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"
]
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
else:
print("Invalid choice. Please select 1 or 2.")
return
if month_name is None:
print(days) # Print the error message
else:
print(f"{month_name} {year} has {days} days")
OUTPUT1:
11
OUTPUT2:
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
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()
return result
else:
return -1
# Example usage
string1 = input("Enter the 1st string: ")
string2 = input("Enter the 2nd string: ")
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.
PROGRAM:
def merge_lists(list1, list2):
# Initialize an empty list to store the merged result
merged_list = []
# 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
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']
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.
AAAABBBBCCCCCCCC 4A4B8C
AABCCA 2A1B2C1A
PROGRAM:
def run_length_encoding(s):
if not s:
return ""
encoded_str = []
count = 1
encoded_str.append(f"{count}{s[-1]}")
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:
[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()
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()))
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
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., ): ")
# 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}%")
break
except ValueError:
print("Invalid input. Please enter only integers separated by commas.")
main()
20
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:
PROGRAM:
sample_data = range(1, 11)
def even():
def odd():
def sum_of_numbers(func=None):
if func:
numbers = func()
else:
22
numbers = sample_data
return sum(numbers)
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.
backward,drawback False
(Reason: character
'a' repeats at position
6, not an anagram)
Reductions,discounter True
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
def get_user_input():
str1 = input("Enter the first string: ")
str2 = input("Enter the second string: ")
if __name__ == "__main__":
str1, str2 = get_user_input()
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 ""
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
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
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', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
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
)
# 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 = []
# 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:
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 y in string:
char_count += 1
count_dict[string] = char_count
return count_dict
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():
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"}
Program:
def find_correct(spelling_dict):
def compare_words(correct, contestant):
if correct == contestant:
return "CORRECT"
35
if len(correct) != len(contestant):
return "WRONG"
if wrong_count <= 2:
return "ALMOST CORRECT"
else:
return "WRONG"
# Initialize counts
correct_count = 0
almost_correct_count = 0
wrong_count = 0
print(f"Correct: {correct_count}")
print(f"Almost Correct: {almost_correct_count}")
print(f"Wrong: {wrong_count}")
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)
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
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")
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}")
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()
except FileNotFoundError:
print(f"The file '{filename}' does not exist.")
return
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:]
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)
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
Program:
def mad_libs():
input_file = "template.txt"
output_file = "output.txt"
placeholders = {
"ADJECTIVE": "adjective",
"NOUN": "noun",
"ADVERB": "adverb",
"VERB": "verb"
}
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
46
def check_eligibility(self):
if self.__experience > 3:
return self.__average_feedback >= 4.5
else:
return self.__average_feedback >= 4
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 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
48
self.__bill_amount = consultation_fees + total_medicine_cost
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:
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
class Cotton(Apparel):
def __init__(self, price):
Apparel.__init__(self, "Cotton", price)
def calculate_price(self):
Apparel.calculate_price(self)
class Silk(Apparel):
def __init__(self, price):
super().__init__("Silk", price)
self.__points = 0
def calculate_price(self):
super().calculate_price()
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()
Output:
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
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:
Program:
import pymysql
mydb = pymysql.connect(
host="localhost",
user="root",
password="Ashish@123",
database="ashishdatabase"
)
mycursor = mydb.cursor()
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()
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()
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()
mycursor.execute(select_query)
rows = mycursor.fetchall()
print("StudentRecord Table:")
for row in rows:
56
print(row)
mydb.close()
Output:
57