0% found this document useful (0 votes)
41 views21 pages

Lab Programs

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)
41 views21 pages

Lab Programs

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/ 21

Experiment-1:

Design a python script to perform the various computations for the amount payable by the
customer for Challenger Computers Store. A customer buying two numbers of SSD device, one
SSD device cost is Rs. 3575/-. The stores offer 15% of the total cost. The customer has to pay
9% CGST, and 9% SGST. Prepare the Net Amount to be payable by the customer.

Program:

ssd_cost = 3575 # Cost of one SSD device in Rs.


num_ssd = 2 # Number of SSD devices
discount_percent = 15 # Discount percentage
cgst_percent = 9 # CGST percentage
sgst_percent = 9 # SGST percentage
total_cost = ssd_cost * num_ssd # Calculate total cost before discount
discount_amount = (discount_percent / 100) * total_cost # Calculate discount amount
discounted_total = total_cost - discount_amount# Calculate discounted total cost
cgst_amount = (cgst_percent / 100) * discounted_total# Calculate CGST and SGST
sgst_amount = (sgst_percent / 100) * discounted_total
total_payable = discounted_total + cgst_amount + sgst_amount # Calculate total amount
print("Cost of one SSD device: Rs.", ssd_cost) # Print the results
print("Number of SSD devices purchased:", num_ssd)
print("Total cost before discount: Rs.", total_cost)
print("Discount (", discount_percent, "% ) applied: Rs.", discount_amount)
print("Discounted total cost: Rs.", discounted_total)
print("CGST (", cgst_percent, "% ) amount: Rs.", cgst_amount)
print("SGST (", sgst_percent, "% ) amount: Rs.", sgst_amount)
print("Net amount payable by the customer: Rs.", total_payable)
Experiment-2:

Design a python script to compute and generate the electricity bill as per the following slab 2)
rates. Collect the meter reading inputs, such as current unit and previous unit. Consumption
Units Rate (in Rupees/Unit)
0-200 3.0
201-250 4.5
251-300 5.2
301-400 6.5
Above 400 7.0

Program:
previous_units = int(input("Enter the previous meter reading: "))
current_units = int(input("Enter the current meter reading: "))
units = current_units - previous_units
bill_amount = 0.0
if units<= 200:
bill_amount = units*3.0
elif units<= 250:
bill_amount = (200*3.0) + (units-200)*4.5
elif units<= 300:
bill_amount = (200*3.0) + (50*4.5) + (units-250)*5.2
elif units<= 400:
bill_amount = (200*3.0) + (50*4.5) + (50*5.2) + (units-300)*6.5
else:
bill_amount = (200*3.0) + (50*4.5) + (50*5.2) + (100*6.5) + (units-400)*7.0
print(“Units Consumed = “,units)
print(f "The electricity bill: Rs. {bill_amount}")
Experiment-3:

Design a python script to display the sum of numbers divisible by 4. The code must allow the
user to accept a number and add it to the sum if it is divisible by 4. It should repeatedly accept
numbers as long as the user wants to provide an input using an appropriate iterative statement
and should display the final sum.

Program:

total_sum = 0
while True:
user_input = input("Enter a number (or type 'exit' or ‘quit’ to finish): ")
if user_input in ['exit','quit’]:
break
number = int(user_input)
if number % 4 == 0:
total_sum += number
print(f"Sum = {total_sum}")
Experiment-4:
Corner home delivers vegetarian and non-vegetarian combos to its customer based on order. A
vegetarian combo costs Rs.120 per plate and a non-vegetarian combo costs Rs.150 per plate.
Their non-veg combo is really famous that they get more orders for their non-vegetarian combo
than the vegetarian combo. Apart from the cost per plate of food, customers are also charged
for home delivery based on the distance in kms from the restaurant to the delivery point. The
delivery charges are as mentioned below:

Given the type of food, quantity (no. of plates) and the distance in kms from the restaurant to
the delivery point, write a python program to calculate the final bill amount to be paid by a
customer. The below information must be used to check the validity of the data provided by
the customer.
• Type of food must be 'V' for vegetarian and 'N' for non-vegetarian.
• Distance in kms must be greater than 0.
• Quantity ordered should be minimum 1.
• If any of the input is invalid, bill amount should be considered as -1.

Program:
veg_rate, non_veg_rate = 120, 150
food_type =input("Enter type of food - V for vegetarian and N for non-vegetarian:")
distance=int(input("Enter distance in kms:"))
qty=int(input("Enter quantity:"))
if food_type in ['V','N'] and distance>0 and qty>=1:
del_charges = None
if distance<= 3:
del_charges = 0
elif distance<=6:
del_charges = (distance-3)*3
else:
del_charges = (3*3) + (distance-6)*6
if food_type=='V':
bill = (veg_rate * qty) + del_charges
else:
bill = (non_veg_rate * qty) + del_charges
else:
bill=-1
print("Delivery Charges =",del_charges)
print("Bill amount=",bill)
Experiment-5:

a). A list has the AP City Names [Tirupati, Kurnool, Kadapa]. Design a python script and
perform the operations like, add 3 more AP City names Chittoor, Nellore, Guntur, insert
Hyderabad in 3rd position, delete any two city names, update all city names as in Uppercase.
Displays the list data, whenever an operation completes.

Program:

ap_cities = ["Tirupati", "Kurnool", "Kadapa"]


print("Initial list of cities:", ap_cities)
ap_cities.extend(["Chittoor", "Nellore", "Guntur"])
print("After adding 3 more cities:", ap_cities)
ap_cities.insert(2, "Hyderabad")
print("After inserting Hyderabad in 3rd position:", ap_cities)
ap_cities.remove("Tirupati")
ap_cities.remove("Nellore")
print("After deleting Tirupati and Nellore:", ap_cities)
ap_cities = [city.upper() for city in ap_cities]
print("After updating all cities to uppercase:", ap_cities)
Experiment-5:

b). Design a python script for given an integer tuple, for each element in the tuple, check
whether there exists a smaller element on the next immediate position of the tuple. If it exists
print the smaller element. If there is no smaller element on the immediate next to the element
then print -1.

Example:
Input: 4 2 1 5 3
Output: 2 1 -1 3 -1

Program:

input_tuple = (4, 2, 1, 5, 3)
result = []
for i in range(len(input_tuple) - 1):
if input_tuple[i] > input_tuple[i + 1]:
result.append(input_tuple[i + 1])
else:
result.append(-1)
result.append(-1)
print("Input:", input_tuple)
print("Output:", result)
Experiment-6:

a). Sets n1 has the data {1, 3, 5, 7, 9}, n2 has the data {9, 5, 6, 8}, wd1=set(["Mon", "Tue",
"Wed", "Thu", "Fri", "Sat", "Sun"]), wd2=set(["Mon", "Tue", "Wed"]). Design a python script
to perform intersection, difference, and symmetric difference operations on the sets n1 and n2,
and to perform superset, and subset operations on the sets wd1, and wd2.

Program:

n1, n2 = {1, 3, 5, 7, 9, {9, 5, 6, 8}


wd1 = set(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])
wd2 = set(["Mon", "Tue", "Wed"])
intersection = n1.intersection(n2)
difference_n1_n2 = n1.difference(n2)
difference_n2_n1 = n2.difference(n1)
symmetric_difference = n1.symmetric_difference(n2)
is_superset_wd1_wd2 = wd1.issuperset(wd2)
is_subset_wd2_wd1 = wd2.issubset(wd1)
print("Intersection of n1 and n2:", intersection)
print("Difference of n1 - n2:", difference_n1_n2)
print("Difference of n2 - n1:", difference_n2_n1)
print("Symmetric Difference of n1 and n2:", symmetric_difference)
print("Is wd1 a superset of wd2?", is_superset_wd1_wd2)
print("Is wd2 a subset of wd1?", is_subset_wd2_wd1)
Experiment-6:

b). The dictionary city_pin has the data {'Tirupati': 517101, 'Hyderabad': 500002, 'Chittoor':
517001,'Nellore': 524001}. Design a python script using lambda function to sort the dictionary
on city name and produce the output and sort the dictionary on pin-code and produce the output.

Program:

city_pin = {'Tirupati': 517101, 'Hyderabad': 500002, 'Chittoor': 517001, 'Nellore': 524001}


sorted_by_city = dict(sorted(city_pin.items(), key=lambda item: item[0]))
sorted_by_pincode = dict(sorted(city_pin.items(), key=lambda item: item[1]))
print("Dictionary sorted by city name:",sorted_by_city)
print("Dictionary sorted by pin-code:",sorted_by_pincode)
Experiment-6:

c). The string has the data, Wel_str = "Welcome to AI ML DS".


Design a python script to search the pattern “AI” using regular expression search and display
the three location numbers of the pattern. First shows the pattern starts location, second shows
the pattern end location, and the last shows pattern span locations.

Program:

import re
Wel_str = "Welcome to AI ML DS"
pattern = re.search(r"AI", Wel_str)
if pattern:
start_location = pattern.start()
end_location = pattern.end()
span_location = pattern.span()
print("Pattern 'AI' starts at location:", start_location)
print("Pattern 'AI' ends at location:", end_location)
print("Pattern 'AI' span locations:", span_location)
else:
print("Pattern 'AI' not found in the string.")
Experiment-7:

a). Design a python script for the mathematical puzzle, Towers of Hanoi. The puzzle has three
rods and n disks. To move the entire stack to another rod, obeying the three rules.
(i) Only one disk can be moved at a time,
(ii) Each move consists of taking the upper disk from one of the stacks and placing it
on top of another stack i.e., a disk can only be moved if it is the uppermost disk on
a stack,
(iii) No disk may be placed on top of a smaller disk.

Program:

def towers_of_hanoi(n, source, auxiliary, target):


if n == 1:
print(f"Move disk 1 from {source} to {target}")
return
towers_of_hanoi(n-1, source, target, auxiliary)
print(f"Move disk {n} from {source} to {target}")
towers_of_hanoi(n-1, auxiliary, source, target)

n = 3 # Number of disks
towers_of_hanoi(n, 'A', 'B', 'C')
Experiment-7:

b). Design a python script to display the numbers that do not appear in the Fibonacci series of
n numbers where n is given by the user. (If n is 8 then up to 8 Fibonacci numbers has to be
printed Ex: 1 1 2 3 5 8 13 21 and in this series missing numbers should be traced and printed.
Ex: missing numbers are: 4 6 7 9 10 11 12 14 15 16 17 18 19.

Program:

def fibonacci_sequence(n):
fib_seq = []
a, b = 1, 1
for _ in range(n):
fib_seq.append(a)
a, b = b, a + b
return fib_seq

def find_missing_numbers(fib_seq, max_num):


missing_numbers = []
for num in range(1, max_num + 1):
if num not in fib_seq:
missing_numbers.append(num)
return missing_numbers

def main():
n = int(input("Enter the number of Fibonacci numbers: "))
fib_seq = fibonacci_sequence(n)
missing_numbers = find_missing_numbers(fib_seq, max_num)
print(f"Fibonacci sequence ({n} numbers): {fib_seq}")
print(f"Missing numbers: {missing_numbers}")

main()
Experiment-8:

a). Design a function Learner_Age_Days with two formal parameters name, age and it
computes Learner’s age in days, then displays learners name and age in days.
(i) Design a driver code to call the function using positional arguments, keyword
arguments.
(ii) (ii) Apply the necessary changes in Learner_Age_Days function, and design a
driver code to call the function using default arguments.

Program:

def Learner_Age_Days(name, age):


age_in_days = age * 365
print(f"{name} is approximately {age_in_days} days old.")

Learner_Age_Days("Alice", 20) # Using positional arguments


Learner_Age_Days(name="Bob", age=25) # Using keyword arguments

Applying Default Arguments:

def Learner_Age_Days(name="Unknown", age=0):


age_in_days = age * 365
print(f"{name} is approximately {age_in_days} days old.")

Learner_Age_Days()
Learner_Age_Days("Charlie")
Learner_Age_Days(age=30)
Experiment-8:

b). Design a python script using lambda and filter functions to construct an odd numbers list
from numbers 1 to 10, and construct a negative numbers list from range of numbers -7 to 7 and
to find the biggest number from a numbers list.

Program: Construct an Odd Numbers List from 1 to 10:

numbers = list(range(1, 11)) # List of numbers from 1 to 10


odd_numbers = list(filter(lambda x: x % 2 != 0, numbers))
print(f"Odd numbers from 1 to 10: {odd_numbers}")

Program: Construct a Negative Numbers List from the Range -7 to 7

range_numbers = list(range(-7, 8)) # Range of numbers from -7 to 7


negative_numbers = list(filter(lambda x: x < 0, range_numbers))
print(f"Negative numbers from -7 to 7: {negative_numbers}")

Program: Find the Biggest Number from a Numbers List

numbers_list = [12, 45, 78, 34, 23, 89, 67]


biggest_number = max(numbers_list, key=lambda x: x)
print(f"The biggest number in the list {numbers_list} is: {biggest_number}")
Experiment-9:

a). Design a python script to create a new file Collect_Literals_Phython.txt, collect the data
from the keyboard about the contents of collection literals list, tuple, sets, dictionaries details,
then write all the data into that file, and then close that file. Afterwards Open the
Collect_Literals_Phython.txt file in read mode, read the entire contents of the file
Collect_Literals_Phython.txt, then display all the contents of that file in monitor.

Program:
def collect_literals():
with open("Collect_Literals_Python.txt", "w") as file:
list_data = input("Enter details about Python lists: ")# Collect data for list
file.write("List details:\n")
file.write(list_data + "\n\n")
tuple_data = input("Enter details about Python tuples: ")# Collect data for tuple
file.write("Tuple details:\n")
file.write(tuple_data + "\n\n")
set_data = input("Enter details about Python sets: ") # Collect data for set
file.write("Set details:\n")
file.write(set_data + "\n\n")
dict_data = input("Enter details about Python dictionaries: ")# Collect data for dictionary
file.write("Dictionary details:\n")
file.write(dict_data + "\n\n")
print("Data has been written to Collect_Literals_Python.txt.")

def display_file_contents():# Function to read and display the contents of the file
with open("Collect_Literals_Python.txt", "r") as file:
contents = file.read()
print("\nContents of Collect_Literals_Python.txt:") # Display the contents of the file
print(contents)

collect_literals()# Main script execution


display_file_contents()
Experiment-9:

b). The file feat_python1.txt has the contents of features of the Python programming language.
Design a python script to open that file feat_python1.txt in read mode, open the new file in
feat_python2.txt in write mode, then read entire contents of the file feat_python1.txt, then copy
all the contents of that file into the new file feat_python2.txt.

Program:

def copy_file_contents():
with open("feat_python1.txt", "r") as source_file: # Open the source file in read mode
content = source_file.read()# Read the entire content of the source file

with open("feat_python2.txt", "w") as dest_file: # Open the destination file in write mode
dest_file.write(content)
print("Contents have been copied from feat_python1.txt to feat_python2.txt.")

copy_file_contents()
Experiment-10:

a). Construct a Python script to implement the below requirements. Create a base class
Basic_Info with data members name, rollno, gender and two member functions getdata() and
display(). Derive a class Physical_Fit from Basic_Info which has data members height and
weight and member functions getdata() and display(). Display all the information using object
of derived class.

Program:

class Basic_Info: # Base class Basic_Info


def __init__(self):
self.name = None
self.rollno = None
self.gender = None

def getdata(self):
self.name = input("Enter name: ")
self.rollno = input("Enter roll number: ")
self.gender = input("Enter gender: ")

def display(self):
print(f"Name: {self.name}")
print(f"Roll Number: {self.rollno}")
print(f"Gender: {self.gender}")

class Physical_Fit(Basic_Info): # Derived class Physical_Fit


def __init__(self):
super().__init__() # Initialize the base class attributes
self.height = None
self.weight = None
def getdata(self):
super().getdata() # Get basic information
self.height = float(input("Enter height (in cm): "))
self.weight = float(input("Enter weight (in kg): "))

def display(self):
super().display() # Display basic information
print(f"Height: {self.height} cm")
print(f"Weight: {self.weight} kg")

person = Physical_Fit()
person.getdata()
person.display()
Eperiment-10:
b). Design a Python script to implement the below specifications, compute, and produce
required output. Define a class REPORT with the following specifications.
Private members:
Admno : 4-digit admission number
Name : 20 characters Marks : A list of 5 floating point values
Average : average marks obtained GETAVG() a function to compute the average obtained in
five subjects.
Public members:
READINFO() function to accept values for Adno, Name, Marks. Invoke the function
GETAVG ().
DISPLAYINFO() function to display all data members of report on the screen.
You should give function definitions.
Write driver code to demonstrate all the functions.

Program:
class REPORT:
__admno = 0
__name = ""
__marks = []
__average = 0.0

def __GETAVG(self):
self.__average = sum(self.__marks) / len(self.__marks)

def READINFO(self):
self.__admno = int(input("Enter 4-digit admission number: "))
self.__name = input("Enter name (max 20 characters): ")[:20]
self.__marks = []
for i in range(5):
mark = float(input(f"Enter mark for subject {i + 1}: "))
self.__marks.append(mark)

self.__GETAVG()
def DISPLAYINFO(self):
print("\n--- Student Report ---")
print(f"Admission Number: {self.__admno}")
print(f"Name: {self.__name}")
print(f"Marks: {self.__marks}")
print(f"Average Marks: {self.__average:.2f}")

# Driver code to demonstrate the functionality


student_report = REPORT()
student_report.READINFO()
student_report.DISPLAYINFO()
Experiment-11:
a). The below scenarios will create Logical Error/Exception, and it will forcibly stop the
execution in middle of the program. Design a Python Script the to handle these operations
exceptions effectively, and avoid to stop the script execution in the middle.
i. The variable num has the data 100, the value of num dividing by the value 0.
ii. ii. To importing a library file matheqn, this library file not available in Python.
iii. A num_List has the values[10,20,30].To print the fifth value of num_List[5]
iv. A dictionary has the data, Dict_Univ = {'1':"MBU", '2':"Tirupathi", '3':"CSE"}. to
print the fifth key value Dict_Univ[5].

Program:
try: # Scenario i: Division by zero
num = 100
result = num / 0
except ZeroDivisionError as e:
print(f"Error: {e}. Division by zero is not allowed.")

try: # Scenario ii: Importing a non-existent library


import matheqn
except ImportError as e:
print(f"Error: {e}. The library 'matheqn' does not exist.")

try: # Scenario iii: Accessing an index that does not exist in a list
num_List = [10, 20, 30]
print(num_List[5])
except IndexError as e:
print(f"Error: {e}. Index 5 is out of range for num_List.")

try: # Scenario iv: Accessing a non-existent key in a dictionary


Dict_Univ = {'1': "MBU", '2': "Tirupathi", '3': "CSE"}
print(Dict_Univ[5])
except KeyError as e:
print(f"Error: {e}. Key 5 does not exist in Dict_Univ.")
Experiment-11:
b). Design a python script to collect the 10 students Python course mark. Check that entered
mark is negative, then throw a user defined exception called Negative, otherwise store into the
mark in the List Python_mark[].

Program:

class Negative(Exception):
def __init__(self, mark):
self.mark = mark
super().__init__(f"Negative marks are not allowed: {mark}")

def collect_marks():
Python_mark = []
for i in range(10):
try:
mark = float(input(f"Enter mark for student {i + 1}: "))
if mark < 0:
raise Negative(mark)
Python_mark.append(mark)
except Negative as e:
print(e)
except ValueError:
print("Invalid input! Please enter a valid number.")

return Python_mark

marks = collect_marks()
print("\nCollected Marks:", marks)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy