324CCS Python LAB Manual Ver1 (1)
324CCS Python LAB Manual Ver1 (1)
Variables (Question 1)
Arithmetic Operators (Questions 2, 3, and 4)
print() function (Questions 5 and 6)
Single – and Double – quoted Strings, triple-quoted Strings (Question 7)
Getting input from the user (Question 8)
Control Statements: If statement (Question 9)
Looping and if-else statement (Question 10)
While loop and if –else (Question 11)
for statement (Question 12)
Iterables, Lists, and Iterators (Question 13)
Q4. Write Python programs to solve the following arithmetic exercises using variables and arithmetic operations.
Calculate the area of a rectangle with a given length and width
Calculate the average of five exam scores
Calculate the total cost of items in a shopping cart with given prices and quantities.
Create variables and assign values as needed for each calculation.
Print the result of each calculation.
Q5. Write a Python program to format your output as per the given instructions.
Create variables with numerical values (e.g., price, quantity, total) and use string formatting to print a statement
that displays these variables with appropriate labels.
(e.g., Price: $20.00, Quantity: 3, Total: $60.00).
Q6. Write a Python program that uses an escape sequence to print the following.
Display a message with a newline character in the middle.
Print a tab-separated list of items.
Print quotes within a String (e.g., “He said, “Hello!””).
10
11
12
Q22. Write a python program that performs following operations on the list of integers.
Remove all even numbers from the list and find Square of each remaining number and calculate the sum of the
squared numbers.
Append the sum to the end of the list.
Print the result.
Hint:
numbers = [2, 3, 4, 5, 6, 7]
output should be like: Modified List: [9, 25, 49, 83]
Q23. Write a Python program that takes two sorted lists as input, merges them into a single sorted list, and displays the
merged list. without using any built-in sorting functions or libraries.
13
Q25. Create a python program file for contact list manager. Create menu-based program that will show user following
options.
Add a new contact
View all contacts
Search for a contact by name
Quit
Create appropriate functions to perform above task and call it properly.
Note: when you add a contact take name and phone number
Q26. Write a Python function that takes a list of integers as input and returns a new list containing the elements at odd
indices (1-based indexing).
Q27. Write a Python function that takes a list of integers as input and removes duplicate elements while preserving the
original order.
Q28. Write a Python function that takes a list of strings as input. The function should perform the following tasks:
Count the number of elements in the list.
Calculate the total length of all the strings in the list.
Find the longest string in the list.
Return these results as a tuple.
Q29. Write a Python function that takes a list of numbers as input and returns a new list containing the cubes of each
number in the original list. and also find sum of all values of new list.
Q30. Write a Python function that takes a list of elements and returns a new list containing the elements in reverse
order. The original list should remain unchanged. Test the function with various types of lists.
14
Q33. Write a Python function that takes a list of strings and character as input. Use the index() method to find and print
the index where a specific character first appears in each string in the list.
Q34. Write a Python program that takes a list of integers and a target integer as input. Use the index() method to find
and print the index of the first occurrence of the target integer in the list. Then, modify the list by removing that
occurrence and repeat the process until all occurrences are found and printed. at end print remaining list.
Q35. Write a Python program that uses a list comprehension to filter out all positive numbers from a given list of
integers.
Q36. Write a Python program that uses a nested list comprehension to create a list of all pairs of numbers from two lists
where the sum of the pair is even.
Q37. Write a Python program that uses list comprehension to generate a list of all prime numbers less than or equal to
a given positive integer n. A prime number is a positive integer greater than 1 that has no positive integer divisors
other than 1 and itself.
Q38. Write a Python program that takes a list of strings and uses a generator expression to generate a sequence of
those strings in uppercase.
Q39. Write a Python program that uses a generator expression to generate a sequence of palindromic numbers within
a specified range (1 to 1000). A palindromic number is a number that remains the same when its digits are reversed.
For example, 121 and 1331 are palindromic numbers.
15
Q41. Write a Python program that takes a list of words and uses the filter() function to filter out anagrams of a given
target word from the list. An anagram is a word formed by rearranging the letters of another word, such as "listen" and
"silent" are anagrams of each other.
Q42. Write a Python program that calculates the factorial of a given positive integer using the reduce() function from
the functools module. The factorial of a number n (denoted as n!) is the product of all positive integers from 1 to n.
Q43. Write a Python program that calculates the greatest common divisor (GCD) of a list of positive integers using the
reduce() function from the functools module. The GCD of a set of numbers is the largest positive integer that divides
each of the numbers without leaving a remainder.
Q44. Write a Python program that creates a 2D list representing a matrix and calculates the sum of each row and
each column. Display the matrix and the sums.
Q45. Write a Python program that takes two 2D lists representing matrices and performs matrix multiplication. Display
both the original matrices and the result.
Q46. Write a Python program that takes a square 2D list representing a matrix and calculates the sum of both the main
diagonal and the anti-diagonal elements (sum of elements on the main diagonal and elements on the diagonal
starting from the top-right corner). Display the original matrix and the sum of diagonals.
16
17
Q49. Write a python program to create a dictionary named inventory that represents the stock of items in a store.
Each item is represented as a dictionary with the item's name as the key and its quantity in stock as the value. Your
task is to perform the following operations:
Use the keys() method to obtain a list of all the item names in the inventory dictionary.
Use the values() method to obtain a list of all the quantities of items in the inventory dictionary.
Calculate and display the total quantity (sum of all quantities) of items in stock.
Q50. Write a python program to create two dictionaries, inventory1 and inventory2, representing the stock levels of
items in two different warehouses. Implement the following operations:
Find items that exist in both warehouses but have different quantities.
Identify items that exist in one warehouse but not in the other.
Q51. Write a python program to create a list of dictionaries, where each dictionary represents a student with attributes
like 'name', 'age', and 'courses'. Implement the following operations using set comprehensions:
Create a set, student_names_set, containing the names of all students.
Create a set, students_with_python_set, containing the names of students who have 'Python' in their list of
courses.
Q52. Write a python program to create two sets, set1 and set2, containing integers. Implement the following
operations:
Find the union of set1 and set2 and store it in a new set, union_set.
Find the intersection of set1 and set2 and store it in a new set, intersection_set.
18
Q53. Write a python program to create three sets, setA, setB, and setC. Implement the following operations:
Determine if setA is a proper subset of setB (i.e., all elements of setA are in setB, but setA is not equal to setB).
Determine if setB is a proper superset of setA (i.e., all elements of setA are in setB, but setB is not equal to setA).
Find and display the symmetric difference between setB and setC.
Create a new set, combined_set, which contains all unique elements from setA, setB, and setC.
Determine if there is any element that is common to all three sets (setA, setB, and setC).
Q54. Write a python program to create two sets vacation_dates and meeting_dates, representing vacation dates and
meeting dates.
Implement the following operations:
Create a set, available_dates, containing the dates that are not overlapping between vacation dates and
meeting dates.
Calculate and display the total number of days available for scheduling.
Q55. Write a python program to manage the membership of a student programming club. You have a mutable set
named club_members containing the student IDs of current club members. The set is initially empty. You also have a
list of dictionaries, new_applications, where each dictionary represents a student who has applied for club
membership. Each dictionary has the following keys: 'student_id', 'name', 'status' (which can be 'accepted' or
'rejected'), and 'courses' (a set of course names).
19
20
Formatting Strings (Presentation Types, Field widths, and Alignment, Numeric Formatting, String’s format Method)
(Questions 56, 57, 58, and 59)
Concatenating and Repeating Strings (Question 60)
Stripping Whitespace from Strings (Question 61)
Changing Character Case (Question 62)
Comparison Operators for Strings (Questions 64, 65)
Searching for Substrings (Question 66)
Replacing Substrings (Questions 67, 68)
Splitting and Joining Strings (Question 69, 70)
Q56. Write a python program for formatting sales data for a report. You have the following information for three
products:
Product 1: Name - "Widget A," Price - $24.95, Quantity Sold - 150
Product 2: Name - "Widget B," Price - $42.99, Quantity Sold - 80
Product 3: Name - "Widget C," Price - $99.50, Quantity Sold - 45
Format the data into a neat table with columns for Product Name, Price per Unit, Quantity Sold, and Total Revenue
for each product. Ensure proper alignment and precision for price and revenue values.
Q57. You are developing a program to print seat numbers for a theater. Each seat is assigned a unique integer value
representing its seat number. Your task is to format these seat numbers for display on tickets.
Format the integer value seat_number to display it as a 3-digit seat number with leading zeros if needed. For
example, if the seat number is 7, it should be formatted as "007."
Use the same formatting for three different seat numbers: 7, 42, and 153.
Write Python code to format these seat numbers using the d presentation type and display the formatted seat
numbers.
21
Format the integer character code 72 as the first character in the message.
Format the integer character code 101 as the second character in the message.
Format the integer character code 108 as the third character in the message.
Format the integer character code 108 again as the fourth character in the message.
Format the integer character code 111 as the fifth character in the message.
Add an exclamation mark (33) at the end of the message.
Write Python code using f-strings to perform these character code conversions and create the final message.
Display the custom message you have created.
Create a sales report table with columns for Product Name, Price per Unit, Quantity Sold, and Total Revenue.
Ensure that the Product Name column is left-aligned within a field of width 15 characters.
Ensure that the Price per Unit column is right-aligned within a field of width 10 characters and displays prices
with two decimal places.
Ensure that the Quantity Sold column is right-aligned within a field of width 15 characters.
Calculate and display the Total Revenue for each product.
Write Python code to format and present this data in the specified table format.
22
Given the user's name "Sarah" and a repetitive pattern string " - Important Notification" concatenate them to
create an email subject.
Similarly, concatenate the user's name "Tom" and the pattern " - Reminder" to create a different email subject.
Additionally, repeat the pattern " 📬" 3 times and concatenate it with the user's name "Emily" to create another
email subject.
Write Python code to concatenate and repeat strings to create the email subjects as specified.
Q61. Write a python program to develop a user registration system where usernames should not contain leading or
trailing spaces. Design a question where students need to validate and clean user-provided usernames to ensure
they meet this requirement.
Q63. Write a Python code to capitalize the first letter of each sentence in the paragraph.
Given paragraph:
"this is a sample paragraph. it contains multiple sentences. each sentence should start with a capital letter. can
you implement this?"
Modified Paragraph:
“This is a sample paragraph. It contains multiple sentences. Each sentence should start with a capital letter.
Can you implement this?”
23
25
Split the text into a list of names using a comma , as the delimiter and store it in a variable called names.
Join the names list back into a single string with names separated by a hyphen -. Store the result in a variable
called hyphen_separated.
Split the text into a list of names using a space ' ' as the delimiter and store it in a variable called
space_separated.
Join the space_separated list back into a single string with names separated by a semicolon ;. Store the result in
a variable called semicolon_separated.
Display the names, hyphen_separated, space_separated, and semicolon_separated variables to verify the
results.
26
Split the employee_data string into a list of individual employee records, where each record is a comma-
separated string.
Iterate through the list of employee records and create a formatted string for each record in the following
format:
o Employee ID: [EmployeeID]
o Name: [FirstName] [LastName]
o Department: [Department]
o Salary: [Salary]
Store each formatted string in a new list called formatted_records.
Join the formatted_records list into a single string where each employee record's information is separated by
two newline characters (\n\n). Store the result in a variable called formatted_data.
Display the formatted_data variable, which contains the formatted employee records, to verify the results.
27
28
29
Division by Zero and Invalid Input, try Statements (Question 74, 75)
Catching Multiple Exceptions in One except Clause (Question 76)
Finally Clause (Question 77, 78)
Explicitly Raising an Exception (Question 79, 80)
Q74. Write a Python program that calculates the average of a list of numbers. However, the program should gracefully
handle two types of errors:
Division by Zero: If the user attempts to calculate the average of an empty list (division by zero), the program
should catch the exception and display a custom error message.
Invalid Input: If the user enters a non-numeric value when adding numbers to the list, the program should catch
the exception and prompt the user to enter a valid numeric value.
Q75. Write a Python program to read a text file data.txt in the following format:
Name, Age, Email
name1, 30, name1@example.com
name2, 25, name2@example.com
name3, 32, name3@example.com
File Not Found Error: If the program attempts to read from a file that does not exist, catch the exception and
display a custom error message.
Data Format Error: If the data in the file does not have the expected format (e.g., missing fields or invalid
values), catch the exception and display a custom error message.
After handling exceptions, display the results of data processing (e.g., the average age) if no exceptions
occurred.
30
Implement a function called perform_operation that takes two user-input numbers (operands) and an operator
(e.g., '+', '-', '*', '/') as arguments. The function should perform the specified operation on the operands and
return the result.
Implement a try block inside the perform_operation function to perform the operation and handle exceptions.
Specifically, you should:
o Handle ValueError if the operands cannot be converted to numbers.
o Handle ZeroDivisionError if the user attempts to divide by zero.
o Handle TypeError if the operator is not a valid arithmetic operator.
Implement a menu-driven program that allows the user to perform arithmetic operations repeatedly. The menu
should include options to add, subtract, multiply, and divide numbers. The program should continue running
until the user chooses to exit.
Q77. Write a Python program to ensure that file resources are always closed properly, even if exceptions occur during
file operations.
Implement a function called copy_file that takes two file names as input: the source file and the destination file.
The function should open the source file for reading and the destination file for writing, and it should copy the
contents of the source file to the destination file.
Use a try block within the copy_file function to perform the file copying operation.
In the finally block, ensure that both the source and destination files are properly closed, regardless of whether
an exception occurs.
Implement a menu-driven program that allows the user to specify the source and destination file names for
copying.
Implement error handling to catch exceptions that may occur during file operations (e.g., file not found,
permission denied) and display appropriate error messages.
31
Choose a resource that needs proper cleanup. It could be anything, such as a network connection, a
database connection, or a hardware device.
Implement a Python function called manage_resource that simulates the management of this resource. Inside
the function, use a try block to perform operations with the resource.
In the except block, handle exceptions that may occur during the resource management (e.g., connection
errors, resource-specific errors). Display appropriate error messages to the user.
Regardless of whether an exception occurs or not, ensure that the resource is released or closed properly in the
finally block.
For your reference giving some function to use in manage_resource() function for demonstrating this task:
def initialize_resource():
resource = connect_to_network()
return resource
def perform_operations_with_resource(resource):
if should_simulate_error():
raise ResourceError("Resource operation failed.")
def release_resource(resource):
disconnect_from_network(resource)
def should_simulate_error():
return False
class ResourceError(Exception):
pass
def connect_to_network():
32
def disconnect_from_network(connection):
print("Disconnecting from the network...")
Q80. Create a Python program that simulates the operation of a vending machine. The vending machine sells various
items, and users can make selections and pay for items.
Define custom exceptions for the following scenarios:
OutOfStockError: Raise this exception when a selected item is out of stock.
InsufficientFundsError: Raise this exception when a user's payment is insufficient to cover the item's cost.
InvalidItemError: Raise this exception when an invalid item selection is made.
Implement a function named vend_item that takes three parameters: selected_item (string), item_stock
(dictionary mapping item names to quantities), and user_payment (float representing the amount the user
paid).
33
Check if the selected item is valid (i.e., exists in the item_stock dictionary). If not, raise the InvalidItemError.
Check if the selected item is in stock (i.e., the quantity is greater than zero). If not, raise the OutOfStockError.
Check if the user's payment is sufficient to cover the item's cost. If not, raise the InsufficientFundsError.
If all conditions are met, deduct one item from the stock and return a success message.
In the main program you can use following dictionaries
item_stock = {"Chips": 5, "Soda": 3, "Candy": 0}
item_prices = {"Chips": 1.50, "Soda": 1.00, "Candy": 0.75}
34
Create a NumPy array power_array containing the squares of the elements in array1 using the np.power()
function.
Compare array1 and array2 element-wise to create a boolean array named comparison_array. Use the ==
operator.
37
38
39
41
42
Database connection using Python, Creating and searching tables content, SQL commands – CREATE, USE, INSERT,
UPDATE, DELETE, DROP, SHOW.
44