[go: up one dir, main page]

0% found this document useful (0 votes)
8 views45 pages

324CCS Python LAB Manual Ver1 (1)

The document is a Python lab manual for a programming course at King Khalid University, detailing topics covered such as variables, control statements, functions, and database programming. It includes instructions for lab activities, assessment methods, and a breakdown of marks for various assessments. Additionally, it outlines specific programming exercises for students to complete in the lab sessions.

Uploaded by

najiwo70
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)
8 views45 pages

324CCS Python LAB Manual Ver1 (1)

The document is a Python lab manual for a programming course at King Khalid University, detailing topics covered such as variables, control statements, functions, and database programming. It includes instructions for lab activities, assessment methods, and a breakdown of marks for various assessments. Additionally, it outlines specific programming exercises for students to complete in the lab sessions.

Uploaded by

najiwo70
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/ 45

324CCS-3 PROGRAMMING WITH PYTHON

PYTHON LAB MANUAL


Department of Computer Science,
College of Computer Science, King Khalid University.
1
Website: https://cs.kku.edu.sa324CCS-3 PROGRAMING WITH PYTHON
Prepared by: Quadri Noorulhasan Naveed
Contact
No List of Topics
Hours
Introduction to Python Programming: Introduction, Variables and Assignment Statements, Arithmetic
1 operators, Function print and an Intro to Single- and Double-Quoted Strings, Triple-Quoted Strings, Getting 2
Input from the User.
Control Statements: Introduction, Algorithms, Pseudocode, Control Statements: if Statement, if…else and
2 if…elif…else Statements, while Statement, for Statement, Iterables, Lists and Iterators, Built-In range 2
Function, Augmented Assignments
Functions: Introduction, Defining Functions, Functions with Multiple Parameters, Random-Number
Generation, Python Standard Library, math functions, Module Functions, Default Parameter Values,
3 4
Keyword Arguments, Arbitrary Argument Lists, Methods: Functions That Belong to Objects, Scope Rules,
importing a module, Passing Arguments to Functions, Functional-Style Programming
Sequences: Lists and Tuples Introduction, Lists, Tuples, Sequence Slicing, del Statement, Passing Lists to
4 2
Functions, Sorting Lists, Searching Sequences, Other List Methods
Dictionaries and Sets:
Dictionaries, creating a Dictionary, Iterating through a Dictionary, Basic Dictionary Operations, Dictionary
5 2
Methods keys and values, Dictionary Comparisons
Sets Comparing Sets, Mathematical Set Operations, Mutable Set Operators and Methods
Strings: A Deeper Look: Formatting Strings (Presentation Types, Field widths, and Alignment, Numeric
Formatting, String’s format Method), Concatenating and Repeating Strings, Stripping Whitespace from
6 Strings, 2
Changing Character Case, Comparison Operators for Strings, Searching for Substrings, Replacing
Substrings, Splitting and Joining Strings
Files: Introduction, Files, Text-File Processing, writing to a Text File: Introducing the with Statement, Reading
7 2
Data from a Text File, Updating Text Files
Handling Exceptions: Division by Zero and Invalid Input, try Statements, Catching Multiple Exceptions in One
8 2
except Clause, finally Clause, Explicitly Raising an Exception
Array-Oriented Programming with NumPy: Creating arrays from Existing Data, array Attributes, Filling arrays
with Specific Values, creating arrays from Ranges, array Operators, NumPy Calculation Methods, Universal
9 6
Functions, Indexing and Slicing, Views: Shallow Copies, Deep Copies, Reshaping and Transposing, Pandas
and Data Visualization Introduction, Series and Data Frames in in pandas.
Database Programming: DBM & SQL What is Database Programming? Installing MySQL server and
10 4
Configuration- Using Python driver for MySQL, Database connection using Python, Creating and searching
2

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
tables content, SQL commands – CREATE, USE, INSERT, UPDATE, DELETE, DROP, SHOW. Programming using
MySQL database - Database Application
11 Matplotlib: Introduction, Getting Started with Pyplot, Matplotlib Subplots, Different types of Plot 2
Total 30

INSTRUCTION FOR ACTIVITIES & ASSESSMENT METHODS


 Laboratory Activities will be conducted every week and activities should be done in the class.
 Lab Assignments will be given and evaluated individually.
 If a student misses the activity, she has to perform an accepted excuse.
 A mini project will be allotted for each Group containing either 2 or 3 students

MARK DISTRIBUTION WITH ASSESSMENT CRITERIA

S. No Assessment Week Due Marks


1 Activities All Weeks 15
2 Mini Project 10-14 5
Total Marks 20

GENERAL LAB INSTRUCTIONS


 All programs/problems to be solved using Python.
 You need to be aware and follow all lab policies and regulations
 For suggestions or mistakes email the instructor or coordinator
 The LAB instructor usually picks one or two problems as exercises, but you are supposed to solve other problems
and study with theory materials
 If you have a laptop, you are allowed to bring it.

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
LAB 1 and 2 / WEEK 1 and 2

TOPICS / LEARNING OBJECTIVES / GOALS

 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)

PROBLEMS / EXERCISES WITH INSTRUCTIONS FOR SOLVING

Q1. Write a Python program as per the given instructions.


 Declare three variables name, age, and student.
 Assign values to these variables with your name, age, and a Boolean indicating whether you are a student or
not.
 Print the values of these variables using the print() function.

Q2. Write a Python program as per the given instructions.


 Declare two variables num1 and num2 and assign them numerical values (e.g., 100 and 50).
 Perform the following arithmetic operations and print the results:
 Addition (num1 + num2)
 Subtraction (num1 - num2)
 Multiplication (num1 * num2)
 Division (num1 / num2)
 Integer Division (num1 // num2)
 Modulo (num1 % num2) and Exponentiation (num1 ** num2)
4

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q3. Write a Python program for displaying the output of the following algebraic expression
𝑎∗4𝑐 2 −𝑑
i.
𝑚+𝑛
8
ii. ab-( c+d )
𝑓

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!””).

Q7. Write a Python program as per the given instructions.


 Use single-quote to print: this is my first “python” program
 Use double-quote to print: this is my second “python” ‘program’
Use triple-quote to print: this ‘is’ my third “python” program

Q8. Write a Python program as per the given instructions.


 Take user input for variable ‘x’ and ‘y’.
 Calculate the value of expression z= 2x2-3xy+y2.
 Display the result.
5

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Output should be like:
Enter the value of 'x': 3.5
Enter the value of 'y': 2.0
The value of the expression z = 2x^2 - 3xy + y^2 for x = 3.5 and y = 2.0 is: 4.75

Q9. Write a Python script as per the given instructions:


 Take user inputs the grades (in integers) of 4 courses from the user.
 Display the average grade of the four courses.
 Print the names and grades of the courses with the highest and the lowest grades.
Note: use only simple if statement

Q10. Create a Python program that performs the following tasks:


 Takes the number of students as input.
 For each student, takes their name and three test scores as input.
 Calculates the average score for each student.
 Assigns a letter grade based on the average score.
 User Input:
 Prompt the user to enter the number of students in the class.
 For each student, prompt the user to enter their name and three test scores.
 Calculate Average Score:
 Calculate the average score for each student using the formula: average = (score1 + score2 + score3) / 3.
 Assign Letter Grades:
Use if-else statements to assign letter grades based on the average score:
 If the average score is 90 or above, assign an 'A'.
 If the average score is between 80 and 89, assign a 'B'.
 If the average score is between 70 and 79, assign a 'C'.
 If the average score is between 60 and 69, assign a 'D'.
 If the average score is below 60, assign an 'F'.

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q11. Create a Python script that performs the following tasks:
 Generates a random number between a specified range (e.g., 1 to 100).
 Asks the user to guess the generated number.
 Provide hints to the user (e.g., "Too high" or "Too low") based on their guesses.
 Continues to prompt the user for guesses until they correctly guess the number.
Note:
 Import the random module to generate random numbers.
 Use the random.randint() function to generate a random number within a specified range (e.g., 1 to 100).
 Use the input() function to prompt the user to enter their guess.
 Convert the user's input to an integer using int().
 Implement a while loop that continues until the user correctly guesses the number.
Inside the loop:
Check if the user's guess is correct.
If the guess is correct, break out of the loop and end the game.
If the guess is incorrect, provide hints (e.g., "Too high" or "Too low") and continue the loop.
Use if-else statements to provide hints to the user based on their guesses.
For example, if the user's guess is higher than the generated number, print "Too high."
Winning Message:
When the user correctly guesses the number, display a winning message with the number of attempts it took.

Q12. Create a Python program that performs the following tasks:


 Takes a user input for the number of Fibonacci numbers to generate.
 Calculates and prints the Fibonacci numbers up to the specified limit.
 Displays the sequence in a user-friendly format.
Note:
 Prompt the user to enter the number of Fibonacci numbers they want to generate.
 Use the input() function to receive user input as an integer.
 Initialize a list fib sequence to store the Fibonacci sequence.
 Use a for loop to generate the Fibonacci sequence up to the specified limit.
 Use the print() function to display the Fibonacci sequence in a user-friendly format.
 Optionally, you can format the output to make it visually appealing.
7

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Output should be like:
Enter the number of Fibonacci numbers to generate: 10

Fibonacci Sequence (first 10 numbers):


0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Q13. Create a Python program to perform the tasks given below.


 Create an empty list named my_list.
 Add the integers from 1 to 5 to my_list.
 Print my_list.
 Append the number 6 to my_list.
 Insert the number 0 at the beginning of my_list.
 Remove the number 3 from my_list.
 Print the modified my_list.

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
LAB 3 / WEEK 3 and 4

TOPICS / LEARNING OBJECTIVES / GOALS

 Built-in range() function (Question 14)


 Defining function and function with parameters (Questions 15, 16, and 17)
 Module Function (Question 18)
 Python Standard library, Math Function (Question 19)
 Function that belongs to Objects (Question 20)
 Random-number generation (Question 21)

PROBLEMS / EXERCISES WITH INSTRUCTIONS FOR SOLVING

Q14. Write a Python program to perform the following tasks.


i. Use the range() function to create a sequence of numbers from 0 to 9. Print the generated sequence.
ii. Create a sequence of numbers from 5 to 14 using the range() function. print the generated sequence.
iii. Create a sequence of even numbers from 2 to 10 using the range() function with a step of 2. print the
generated sequence.
iv. Use the list() function to convert a range() object into a list. print the resulting list.
v. Create a for loop that uses the range() function to iterate from 1 to 5. print each iteration.
vi. Create a sequence of numbers from 10 to 1 in reverse order using the range() function. print the generated
sequence.
vii. Create a sequence of numbers from 100 to 1 with a negative step of -10 using the range() function. print the
generated sequence.
viii. Use the range() function to generate a sequence of even numbers from 2 to 100. calculate and print the
sum of these even numbers.
ix. Create a program that generates a multiplication table for a specified number using the range() function
and a for loop.

Q15. Create a python program to perform given tasks.


 Create a simple function named greet() that prints a greeting message (e.g., "Hello, World!") when called. Call
the greet() function to test it.
9

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
 Create a function named square() that takes an integer as a parameter and returns its square.
 Create a function named calculate_area() that calculates the area of a rectangle given its length and width as
parameters. call the calculate_area() function with different length and width values and print the results.
 Modify the greet() function to have a default name parameter. If no name is provided, it should greet "World."
call the greet() function without and with a name argument.
 Create a function named add() that takes two numbers as parameters and returns their sum. call the add()
function with different number pairs and print the results.

Q16. Create a Python program to perform given tasks.


 Create a function named factorial() that calculates the factorial of a given positive integer using a loop. call
the factorial() function with different integer values and print the results.
 Create a function named is_palindrome() that checks if a given string is a palindrome (reads the same forwards
and backward). call the is_palindrome() function with different strings and print the results.

Q17. Create a Python script to perform the following tasks.


 Create a function named calculate_rectangle_area() that calculates the area of a rectangle given its length
and width. call the calculate_rectangle_area() function with various length and width values and display the
results.
 Develop a function named calculate_circle_properties() that takes the radius as input and returns both the
circumference and area of the circle. call the calculate_circle_properties() function and display both values.
Note: circumference = 2* pi*radius
Area = pi * radius * radius

Q18. Create a Python program to perform given tasks.


 Create a new Python file named “math_functions.py”
 Inside math_functions.py define following functions add(x,y), subtract(x,y), multiply(x,y), divide(x,y), power(x,y),
factorial(n).
 Create a new Python script named main.py in the same directory
 Import the math_functions module into main.py.
Call all methods in main.py with the value of your choice and print the result.

10

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q19. Write a Python program to perform the following tasks.
i. Calculates the square root of a given number using the math.sqrt() function.
ii. Calculate the absolute value of -15 using the math.abs() function.
iii. Round the number 3.75 to the nearest integer using the math.round() function.
iv. Write a Python function that takes an angle in degrees as input and calculates its sine using the math.sin()
function
v. Calculate the cosine of 60 degrees using the math.cos() function.
vi. Find the tangent of 45 degrees using the math.tan() function.
vii. Calculate the circumference of a circle with a radius of 5 units using the math.pi constant. (Note:
circumference = 2* pi*radius).
viii. Compute the area of a circle with a radius of 2.5 units using the math.pi constant. (Note: Area = pi * radius *
radius)
ix. Write a Python function that takes a number as input and calculates its exponential value using the
math.exp() function.
x. Write Python code that calculates the factorial of a given integer using the math.factorial() function.
xi. Determine the greatest common divisor (GCD) of two numbers, 36 and 48, using the math.gcd() function.
xii. Write Python code that calculates the mean of a list of numbers using the math.mean() function.
Generate a random integer between 1 and 100 using the random.randint() function from the random module.

Q20. Write a Python script, that performs the following tasks.


 Create a function called swap_first_last that accepts a list as an argument and swaps the positions of the first
and last elements in the list. Return the modified list.
 Create a function called concatenate_strings that accepts a list of strings as an argument and returns a single
string obtained by concatenating all the strings in the list.
 Create a function called calculate_average that accepts a list of numbers as an argument and returns the
average of those numbers.
 Create a function called filter_even_numbers that accepts a list of integers as an argument. The function should
filter out and return a new list containing only the even numbers from the input list

11

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q21. Write a Python program to perform the following tasks.
 Create a Python quiz program that presents random questions to the user and records their score.
 Define quiz questions, and answers using lists.
 Combine questions and answers into a list of tuples. (Hint: quiz = list(zip(questions, answers))
 Shuffle the quiz questions. Hint use random.shuffle()
 Define run_quiz(quiz) method, in this method, show the question to the user and take user_answer, compare
user_answer with the correct answer in the list, if matches increase the score by 1, this method should return the
score. (Hint, user for loop to iterate)
 Call run_quiz() method and print score.

12

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
LAB 4 / WEEK 5

TOPICS / LEARNING OBJECTIVES / GOALS

 Lists (Question 22, 23)


 Tuples (Questions 24, 25)
 Sequence Slicing (Question 26, 27)
 Passing Lists to Functions (Question 28, 29 and 30)
 Sorting Lists (Question 31, 32)
 Searching Sequences (Question 33, 34)
 List Comprehensions (Question 35, 36)
 Generator Expressions (Question 38, 39)
 Filter, Map and Reduce (Question 40, 41, 42 and 43)
 Two-Dimensional Lists (Question 44, 45 and 46)

PROBLEMS / EXERCISES WITH INSTRUCTIONS FOR SOLVING

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

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q24. Write a Python function that takes a list of tuples as input. Each tuple in the list represents a person's name and
age. The function should return a new list of tuples where each tuple contains the person's name and their age
increased by 5 years.

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

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q31. Write a Python program that takes a list of strings as input and sorts it in descending order. Print the sorted list of
words.
Q32. Write a python program with a list of tuples, where each tuple contains the student's name (string), exam score
(integer), and age (integer). Perform following.
 Sort the list by exam score in ascending order
 If multiple students have the same exam score, sort them by age in descending order.
 For students with the same exam score and age, sort them alphabetically by name in ascending order.

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

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q40. Write a Python program that uses the map() function to apply a custom function to each element of a given list
of strings. The custom function should count the number of vowels in each string and return the count.

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

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
LAB 5 / WEEK 6

TOPICS / LEARNING OBJECTIVES / GOALS

 Dictionaries (Question 47)


 Dictionary Methods keys and values (Question 48, 49)
 Dictionary Comparisons (Question 50)
 Sets (Question 51)
 Mathematical Set Operations (Question 52, 53 and 54)
 Mutable Set Operators and Methods (Question 55)

PROBLEMS / EXERCISES WITH INSTRUCTIONS FOR SOLVING

Q47. Write a python program to perform following:


 Create an empty dictionary called student_scores and add the following student names and their
corresponding scores:
Ali: 85
Ahmed: 92
Sayeed: 78
Fatima: 95
 Write a Python program to iterate over the student_scores dictionary and print the names of students who
scored more than 80.
 Create a dictionary called city_population to store the populations of the following cities:
Riyadh: 8,405,837
Jeddah: 3,979,576
Abha: 2,705,994
 Write a Python program to find the population of a specific city (e.g., " Abha") from the city_population
dictionary.
 Calculate the average population of all the cities in the city_population dictionary and print the result.

17

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q48. Create a reservation system for a restaurant. Implement the following operations using dictionaries:
 Allow customers to make reservations by specifying their name and the number of guests in their party for a
specific date and time.
 Check if a reservation already exists for a given date and time. If it does, inform the customer that the time slot
is already booked.
 Cancel a reservation by specifying the customer's name and the date and time of their reservation.
 Display the reservations for a specific date, sorted by the reservation time.

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

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
 Find the symmetric difference of set1 and set2 and store it in a new set, symmetric_difference_set.
 Determine if set1 is a subset of set2.
 Determine if set2 is a superset of set1.

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).

Implement the following operations:

19

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
 add the 'student_id' of students with 'status' as 'accepted' to the club_members set.
 For each student in the new_applications list with 'status' as 'rejected', remove them from the club_members set
if they were previously members.
 For each student in the new_applications list with 'status' as 'accepted', check if they have enrolled in at least
one programming-related course (courses like 'Python', 'Java', 'C++'). If so, add them to a separate set called
programming_club_members.
 Clear the club_members set to remove all members (for a fresh start). Print before clearing.
 Display the final club_members set (which should be empty after clearing) and the
programming_club_members set, which should contain the student IDs of those who have enrolled in
programming-related courses.

20

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
LAB 6 / WEEK 7

TOPICS / LEARNING OBJECTIVES / GOALS

 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)

PROBLEMS / EXERCISES WITH INSTRUCTIONS FOR SOLVING

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

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q58. You need to develop a program to create a custom message by combining characters from integer character
codes. Using f-strings and the c presentation type, format the following integer character codes into a single string:

 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.

Q59. Given the top-selling products and their sales data:

Product 1: Name - "Widget X," Price - $19.99, Quantity Sold - 250


Product 2: Name - "Widget Y," Price - $29.95, Quantity Sold - 180
Product 3: Name - "Widget Z," Price - $39.99, Quantity Sold – 120

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

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q60. Develop a program that generates email subjects with specific patterns. Each subject consists of a user's name
followed by a repetitive pattern.

 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.

Q62. Write a python program to perform following:


 Given the string text = "Hello, World!", write Python code to convert all characters in text to uppercase using the
upper() method.
 Given the string text2 = "This is a sample sentence.", write Python code to convert all characters in text2 to
lowercase using the lower() method.
 Create a string text3 with the value "programming in python". Write Python code to convert the first letter of
each word in text3 to uppercase using the title() method.
 Display the modified strings after changing their character cases.

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

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q64. Write a Python code to perform followings:
 Given two strings: string1 = "apple" and string2 = "apricot", use comparison operators to determine which string
comes first in lexicographic (dictionary) order.
 Compare two strings: string3 = "programming" and string4 = "programmer", and determine which string comes
first.

Q65. Write a Python code to perform followings:


 Prompt the user to enter a username and store it in a variable called user_input_username.
 Prompt the user to enter a password and store it in a variable called user_input_password.
 Check if the user_input_username is equal to "admin" (case-insensitive comparison) and user_input_password is
equal to "Password123" (case-sensitive comparison). If both conditions are met, print "Access granted.
Welcome, admin!" Otherwise, print "Access denied. Invalid credentials."
 Extend your code to include the following security checks:
 Check if the length of the user_input_password is at least 8 characters. If it's less than 8 characters, print "Weak
password. Password should be at least 8 characters long."
 Check if the user_input_password contains at least one uppercase letter, one lowercase letter, and one digit. If
any of these criteria are not met, print "Weak password. Password should contain at least one uppercase letter,
one lowercase letter, and one digit."

Q66. Write a python program to perform followings:


Given:
text = "Python is a versatile programming language used for web development, data analysis, and more. Python is
known for its simplicity and readability."
 Use the count() method to:
o Count the number of occurrences of the word "Python" in the text.
o Count the number of occurrences of the word "is" in the text.
 Use the index() method to:
o Find the starting index of the first occurrence of "programming" in the text.
o Find the starting index of the second occurrence of "Python" in the text.
 Use the rindex() method to:
o Find the starting index of the last occurrence of "Python" in the text.
24

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
o Find the starting index of the last occurrence of "analysis" in the text.
 Use the startswith() method to:
o Check if the text starts with the word "Python." Print "Starts with Python" if it does, otherwise print "Does not
start with Python."
 Use the endswith() method to:
o Check if the text ends with the word "readability." Print "Ends with readability" if it does, otherwise print
"Does not end with readability."
 Use the find() method to:
o Find the starting index of the first occurrence of "AI" in the text. If found, print the index; otherwise, print "AI
not found."
o Find the starting index of the word "development" starting from index 20 in the text. If found, print the
index; otherwise, print "Development not found after index 20."
o Extract and print the substring that starts at the index where "known" begins and ends at the index where
"simplicity" ends (inclusive). Use string slicing to accomplish this.
o Check if the text contains the word "data science" using the in operator. If it does, print "Contains 'data
science'"; otherwise, print "Does not contain 'data science'.

Q67. Write Python code implement following tasks:


Given text = "The quick brown fox jumps over the lazy dog. The fox is quick, but the dog is not."
 Create a list of rules where each rule is a tuple containing a search string and a replacement string.
 Define the following rules:
o Replace "quick" with "fast."
o Replace "fox" with "animal."
o Replace "dog" with "creature."
o Replace "brown" with "red."
 Implement a function apply_rules(text, rules) that takes the text and rules list as input and returns the text with
the specified replacements applied. The function should iterate through the rules and apply each replacement
in order.
 Use the apply_rules() function to process the text with the defined rules.
 Display the modified text after applying all the rules.

25

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q68. Write Python code to implement following tasks:
given:
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vehicula, massa nec efficitur aliquet, libero arcu
tristique odio, in tincidunt felis est vel libero."

 Replace all occurrences of "Lorem" with "Introduction."


 Replace all occurrences of "ipsum" with "Lorem."
 Replace all occurrences of "elit" with "important."
 Replace all occurrences of "Duis" with "Furthermore."
 Replace all occurrences of "adipiscing" with "reading."
 Replace all occurrences of "efficitur" with "efficient."
 Replace all occurrences of "tincidunt" with "content."
 Replace all occurrences of "felis" with "also."
 Finally, display the modified text.

Q69. Write Python code to implement following:


For given following text:
text = "Jan, Feb, March, April, May"

 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

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q70. Write a Python program to create a string variable employee_data
like:
employee_data=EmployeeID,FirstName,LastName,Department,Salary
101,Alice,Smith,HR,50000
102,Bob,Jones,IT,60000
103,Carol,Williams,Finance,55000
104,David,Brown,IT,62000

 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

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
LAB 7 / WEEK 8

TOPICS / LEARNING OBJECTIVES / GOALS

 Files, Text-File Processing (Question 71)


 Writing to a Text File: Introducing the with Statement, Reading Data from a Text File (Question 72)
 Updating Text Files (Question 73)

PROBLEMS / EXERCISES WITH INSTRUCTIONS FOR SOLVING

Q72. Write a python program to implement following:


Create a text file named inventory.txt and write initial product records to it. Each product record should be in the
following format:
ProductID,ProductName,Price,Stock
101,product1,10.99,100
102,product2,24.95,50
103,product3,15.49,75
104,product4,5.99,200
 Write code to create the file and write these records into it.
 Implement a function called read_inventory that reads the product records from the inventory.txt file and
returns them as a list of dictionaries. Each dictionary should represent a product with keys for "ProductID,"
"ProductName," "Price," and "Stock."
 Write code to call the read_inventory function and display the product records on the console in a user-friendly
format.
 Allow the user to add a new product to the inventory.txt file. Prompt the user to enter the product's information
(ProductID, ProductName, Price, and Stock) and add it to the file.
 Display the updated product records after adding the new product

28

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q73. Write a python code to implement following tasks.
 Create an empty text file named tasks.txt.
 Implement a function called add_task that allows a user to add a new task to the text file. The user should input
the task description, and the code should generate a unique task ID for each task. The task ID should be an
incremental number starting from 1. After adding a task, the text file should be updated with the new task.
 Implement a function called list_tasks that reads the contents of the tasks.txt file and displays all tasks, including
their task IDs and descriptions, on the console.
 Implement a function called update_task that allows a user to update the description of a specific task. The
user should input the task ID of the task to be updated, and the new description. After updating the task, the
text file should be updated with the changes.
 Implement a function called delete_task that allows a user to delete a specific task by providing its task ID.
After deleting the task, the text file should be updated without the deleted task.
 Create a menu-driven program that allows the user to perform the following actions:
o Add a new task
o List all tasks
o Update a task
o Delete a task
o Exit the program
o Ensure that the program continues to run until the user chooses to exit.
 Test your program by adding, listing, updating, and deleting tasks, and verify that the text file is updated
correctly after each operation.

29

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
LAB 8 / WEEK 9

TOPICS / LEARNING OBJECTIVES / GOALS

 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)

PROBLEMS / EXERCISES WITH INSTRUCTIONS FOR SOLVING

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

You need to handle the following exceptions:

 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

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q76. Write a Python program that performs various operations on user-input numbers. Your task is to enhance the
program's error handling by catching multiple types of exceptions in a single except clause. Specifically, you should
handle ValueError, ZeroDivisionError, and TypeError exceptions.

 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

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q78.Write a Python program that manages resources and need to ensure that these resources are properly released,
even if an exception occurs. Your task is to demonstrate your understanding of the finally clause.

 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

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
print("Connecting to the network...")
return "Network Connection"

def disconnect_from_network(connection):
print("Disconnecting from the network...")

Q79. Write a python program to perform following tasks:


 Create a Python function named calculate_average that takes a list of numbers as input.
 Inside the calculate_average function, calculate the average of the numbers in the list.
 Use exception handling to handle the following scenarios within the function:
 If the input list is empty, raise a custom exception named EmptyListError with the message "The list is empty.
Cannot calculate the average."
 If any of the numbers in the list is negative, raise a custom exception named NegativeNumberError with the
message "Negative numbers are not allowed in the list."
 Call the calculate_average function with a valid list of numbers and display the calculated average.
 Call the calculate_average function with an empty list and handle the EmptyListError exception.
 Call the calculate_average function with a list containing negative numbers and handle the
NegativeNumberError exception.
 Make sure to include the try, except, and raise statements to demonstrate your understanding of explicitly
raising exceptions.

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

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
 Inside the vend_item function, use exception handling to:

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

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
LAB 9 / WEEK10, 11 and 12

TOPICS / LEARNING OBJECTIVES / GOALS

 Creating arrays from Existing Data (Question 81, 82)


 array Attributes, Filling arrays with Specific Values, Creating arrays from Ranges (Question 83, 84 and 85)
 array Operators (Question 86)
 NumPy Calculation Methods (Question 87, 88 and 89)
 Universal Functions (Question 90, 91 and 92)
 Indexing and Slicing (Question 93, 94)
 Views: Shallow Copies, Deep Copies (Question 95)
 Reshaping and Transposing (Question 96)
 Series and Data Frames in pandas (Question 97, 98, 99 and 100)

PROBLEMS / EXERCISES WITH INSTRUCTIONS FOR SOLVING

Q81. Write a python script to perform following tasks:


 Create a NumPy array from the following list: [10, 20, 30, 40, 50].
 Create a NumPy array from the following tuple: (5, 10, 15, 20, 25).
 Create a NumPy array with 5 zeros.
 Create a NumPy array with 3 ones.
 Generate a NumPy array containing the values from 5 to 15 (inclusive) with a step size of 2.
 Create a 2x2 NumPy array of random float values between 0 and 1.
 How can you create a 3x3 NumPy array filled with a specific value, such as 7?
 Create a NumPy array with the first 10 even numbers.

Q82. Write a python program to perform following tasks:


 Given a NumPy array arr = np.array([1, 2, 3, 4, 5, 6]), how can you reshape it into a 2x3 array?
 Create a NumPy array containing 5 random integers between 1 and 100.
 Create a NumPy array and then extract the even-indexed elements from it.
Q83. Write a python program to perform following tasks :
 Create a NumPy array called my_array using the following list of integers: [5, 10, 15, 20, 25].
35

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
 Access the following attributes of my_array and print their values:
o Shape
o Number of dimensions (ndim)
o Data type (dtype)
o Total number of elements (size)

Q84. Write a python program to perform following tasks:


 Create a NumPy array filled with the constant value 9. The array should have a shape of (3, 3). Provide both the
code and the resulting array.
 Generate a NumPy array of zeros with a shape of (2, 4, 2). What is the total number of elements in this array?
 Create a NumPy array filled with ones. The array should have a shape of (5, 5). What is the value at the third
row and fourth column?

Q85. Write a python program to perform following tasks:


 Create a NumPy array called sequence_array containing the following sequence of numbers: 10, 15, 20, 25, 30,
..., 100. You should use a range-based method to generate this sequence. The array should have a shape of
(5,).
 Generate a NumPy array named arithmetic_array containing the first 10 terms of the arithmetic progression
with a common difference of 3. The first term should be 7.
 Create a NumPy array called geometric_array representing the first 8 terms of a geometric progression with a
common ratio of 2. The first term should be 2.
 Use NumPy to create an array named fibonacci_array containing the first 12 Fibonacci numbers starting from 0
and 1.
 Generate a NumPy array called odd_square_array containing the squares of all odd numbers from 1 to 20.

Q86. Write a python program to perform following tasks:


 Create two NumPy arrays, array1 and array2, with the following values:
 array1: [1, 2, 3, 4, 5]
 array2: [5, 4, 3, 2, 1]
 Perform the following operations using array operators and functions:
o Add array1 and array2 element-wise and store the result in a variable add_result.
36

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
o Subtract array2 from array1 element-wise and store the result in a variable subtract_result.
o Multiply array1 and array2 element-wise and store the result in a variable multiply_result.
o Divide array1 by array2 element-wise and store the result in a variable divide_result.

 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.

Q87. Write a python program to perform following tasks:


Create a NumPy array named data with the following values:
[25, 32, 42, 18, 56, 30, 24, 40, 38, 20]
Use NumPy's calculation methods to perform the following calculations:
 Calculate and store the mean of the data array in a variable mean_value.
 Compute and store the median of the data array in a variable median_value.
 Find and store the standard deviation of the data array in a variable std_deviation.
 Determine and store the sum of all elements in the data array in a variable sum_value.
 Calculate and store the maximum and minimum values in the data array in variables max_value and
min_value, respectively.
 Print the results of each calculation to verify their accuracy.

Q88. Write a Python script to perform followings:


Suppose you have a dataset containing the monthly sales figures for a year. You can use monthly_sales array data
having following values [25, 32, 42, 18, 56, 30, 24, 40, 38, 20]
Perform following tasks by using NumPy to calculate the following statistics:
 Monthly average sales.
 Total annual sales.
 Standard deviation of monthly sales.
 Month with the highest sales.
 Month with the lowest sales.

37

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q89. Write a python program to perform task:
You are working with a large dataset of student exam scores in various subjects. How would you use NumPy to
calculate the following statistics:
 Overall average score across all subjects.
 Standard deviation of scores in a specific subject.
 The subject with the highest average score.
 The subject with the lowest average score.
 The top-performing student and their average score.

Q90. Write a python program to perform following tasks:


 Create a NumPy array named data with the following values:
[10, 15, 20, 25, 30]
 Calculate and store the square root of each element in the data array in a new array called sqrt_result.
 Calculate and store the exponential of each element in the data array in a new array called exp_result.
 Calculate and store the natural logarithm (base e) of each element in the data array in a new array called
log_result.
 Calculate and store the sine of each element in the data array in a new array called sin_result.
 Calculate and store the floor value (rounding down) of each element in the data array in a new array called
floor_result.
 Print the values of each result array to verify their contents.

Q91. Write a python program to perform following tasks:


You are working with a dataset that contains stock prices over time.
you can use array by name stock_prices having following elements [100, 105, 102, 98, 103, 110, 112, 108, 105, 110]
Explain how you can utilize NumPy ufuncs to perform the following operations:
 Calculate the daily percentage change in stock prices.
 Identify days with the highest percentage price increase.
 Determine the moving average of stock prices over a specific time window.
 Find the day with the maximum absolute price change.

38

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q92. Write a python program to perform following tasks:
you have been given monthly sales figures for multiple products over several years.
use: sales_data for three years
[5000, 5200, 5500, 5400, 5600],
[3000, 3200, 3500, 3300, 3400],
[7000, 7100, 7200, 7400, 7500]
use NumPy ufuncs to perform the following analyses:
 Calculate the compound growth rate for each product's sales.
 Identify the product with the highest average sales growth rate.
 Determine the months with the highest and lowest sales figures.
 Find the month with the maximum increase in sales compared to the previous month.

Q93. Write a python program to perform following tasks:


Create a NumPy array named data with the following values:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Use NumPy indexing and slicing to perform the following tasks:
 Extract and print the first element of the data array.
 Extract and print the last element of the data array.
 Extract and print a slice of the data array containing elements from index 2 to 5 (inclusive).
 Extract and print a slice of the data array containing elements from index 3 to the end.
 Extract and print a slice of the data array containing every other element (even-indexed elements).

Q94. Write a python program to perform following tasks:


You have a 3D NumPy array representing a volumetric dataset of temperature values at different points in space.
The array has dimensions (x, y, z), where x, y, and z represent spatial coordinates.
perform the following advanced tasks:
 Extract a vertical cross-section (y-z plane) at a specific x-coordinate (e.g., x=50) and display it as a 2D
heatmap.
 Calculate the average temperature across all spatial coordinates and display it as a single value.
 Identify the spatial coordinates (x, y, z) with the highest and lowest temperatures.

39

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
 Explain the NumPy indexing and slicing techniques and functions you would use to accomplish these
advanced tasks on the 3D volumetric dataset.
Q95. Write a python program to perform following tasks:
Create a NumPy array named original_array with the following values:
[10, 20, 30, 40, 50]
Use NumPy to perform the following tasks:
 Create a view of the original_array and assign it to a variable named array_view. Modify one element in the
array_view and check if it affects the original_array.
 Create a shallow copy of the original_array and assign it to a variable named shallow_copy. Modify one
element in the shallow_copy and check if it affects the original_array.
 Create a deep copy of the original_array and assign it to a variable named deep_copy. Modify one element
in the deep_copy and check if it affects the original_array.
 You need to check and print:
o Does the view affect the original_array?
o Does the shallow copy affect the original_array?
o Does the deep copy affect the original_array?

Q96. Write a python program to perform followings:


Create a NumPy array named original_array with the following values:
[10, 20, 30, 40, 50, 60, 70, 80]
Use NumPy to perform the following tasks:
a) Reshape the original_array into a 2x4 array (2 rows and 4 columns). Print the reshaped array.
b) Transpose the reshaped array from task (a) to switch its rows and columns. Print the transposed array.
c) Flatten the original_array into a 1D array (single row). Print the flattened array.
d) Reshape the flattened array from task (c) into a 2x4 array. Print the reshaped array.

Q97. Write a Python program to perform followings:


Create a Series named population with the population data of five cities:
City A: 1000000
City B: 750000
City C: 1200000
40

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
City D: 900000
City E: 650000
Use the Series to answer the following questions:
 Print the population of City C.
 Determine which city has the highest population.
 Calculate the total population of all cities.

Q98. Write a Python program to perform followings:


Create a Data Frame named student_data with the following columns:
"Student ID": [101, 102, 103, 104, 105]
"Name": ["Alice", "Bob", "Charlie", "David", "Eve"]
"Age": [20, 22, 21, 23, 19]
"Grade": ["A", "B", "B", "A", "C"]
Use the Data Frame to answer the following questions:
 Display the entire Data Frame.
 Print the age of the student with a Student ID of 103.
 Find the number of students who received a grade "A."
 Calculate the average age of the students.

Q99. Write a Python program to perform following tasks:


Suppose you have dataset containing daily stock prices for a particular company over several years.
Create a DataFrame from the dataset with the following columns:
"Date" (containing date values)
"Stock Price" (containing the stock prices)
Note: Create a DataFrame with time series data
Your tasks are as follows:
 Calculate the average stock price for each year.
 Identify the year with the highest average stock price.
 Calculate the monthly volatility (standard deviation of stock prices) for the most recent year.

41

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
Q100. Write a pPython program to perform followings:
You are given a DataFrame that contains information about customer orders.
The DataFrame includes columns for customer ID, order date, product ID, quantity, and price per unit.
Customer ID: [101, 102, 101, 103, 102, 104, 103],
Order Date: ['2021-01-01', '2021-01-05', '2021-01-10', '2021-02-15', '2021-02-20', '2021-03-01', '2021-03-05']
Product ID: ['A', 'B', 'A', 'C', 'B', 'A', 'C']
Quantity: [2, 3, 1, 2, 4, 2, 1]
Price per Unit': [10.0, 15.0, 10.0, 20.0, 15.0, 10.0, 20.0]
Your tasks are as follows:
 Calculate the total revenue for each customer.
 Identify the top 5 customers with the highest total revenue.
 Calculate the total revenue for each product.
 Identify the top 3 products with the highest total revenue.

42

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
LAB 10 / WEEK 13 and 14

TOPICS / LEARNING OBJECTIVES / GOALS

Database connection using Python, Creating and searching tables content, SQL commands – CREATE, USE, INSERT,
UPDATE, DELETE, DROP, SHOW.

PROBLEMS / EXERCISES WITH INSTRUCTIONS FOR SOLVING

Q21. Write a Python script to perform followings:


 Establish a connection to the MySQL database:
 Execute SQL queries to perform the following tasks:
 Create a table named "students" with columns "id" (integer) and "name" (varchar).
 Insert four sample records into the "students" table.
 Query the "students" table to retrieve all records.
 Update a record in the "students" table.
 Delete a record from the "students" table.

Q22. Write a Python program to perform following tasks:


Insert the following records into a "books" table in a MySQL database:
Title: "Python Programming", Author: "Ravindran", Price: 29.99
Title: "Database Design", Author: "R Champ", Price: 39.95
Title: "Web Development", Author: "B Kavish", Price: 24.99
 Retrieve and print all records from the "books" table in a MySQL database. Assume that the table contains
columns for "Title," "Author," and "Price."
 Update the price of the book titled "Python Programming" to $19.99 in the "books" table in a MySQL database.
Make sure to commit the changes.
 Delete the record for the book titled "Web Development" from the "books" table in a MySQL database. Ensure
that the deletion is committed.
43

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
LAB 11 / WEEK 15

TOPICS / LEARNING OBJECTIVES / GOALS

 Built-in range() function (Question 14)


 Defining function and function with parameters (Questions 15, 16, and 17)
 Module Function (Question 18)
 Python Standard library, Math Function (Question 19)
 Function that belongs to Objects (Question 20)
 Random-number generation (Question 21)

PROBLEMS / EXERCISES WITH INSTRUCTIONS FOR SOLVING

44

324CCS-3 PROGRAMING WITH PYTHON


Prepared by: Quadri Noorulhasan Naveed
If you have any insights or suggestions about this LAB manual,
I would love to hear them.
Quadri Noorulhasan Naveed
Email: qnaveed@kku.edu.sa
Office: B13-2-28,
Department of Computer Science,
College of Computer Science, King Khalid University,
https://cs.kku.edu.sa

You might also like