0% found this document useful (0 votes)
4 views71 pages

Practical File Cs

The document provides practical Python and SQL solutions for Class 12 students, covering various programming tasks such as counting palindrome words, finding the smallest and longest words in a sentence, converting sentences to title case, and working with tuples and dictionaries. Each task includes a question, solution code, and example outputs. The solutions demonstrate fundamental programming concepts and techniques in Python, making it a useful resource for students learning these topics.

Uploaded by

vishu2611
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)
4 views71 pages

Practical File Cs

The document provides practical Python and SQL solutions for Class 12 students, covering various programming tasks such as counting palindrome words, finding the smallest and longest words in a sentence, converting sentences to title case, and working with tuples and dictionaries. Each task includes a question, solution code, and example outputs. The solutions demonstrate fundamental programming concepts and techniques in Python, making it a useful resource for students learning these topics.

Uploaded by

vishu2611
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

Python and SQL Practical Solutions -

Class 12

1. Palindrome Words Count

• Question: WAP to enter a sentence (string) and count total palindrome words present in
it.

• Solution Code:

Python

def is_palindrome(word):

return word == word[::-1]

sentence = input("Enter a sentence: ")

words = [Link]().replace('.', '').replace(',', '').split()

palindrome_count = 0

for word in words:

if word and is_palindrome(word):

palindrome_count += 1

print(f"Total palindrome words: {palindrome_count}")

Output:

Enter a sentence: Madam Arora teaches Malayalam. racecar

Total palindrome words: 3

2. Smallest Word

• Question: WAP to enter a sentence (string) and display the smallest word.

• Solution Code:

Python

sentence = input("Enter a sentence: ")

words = [Link]()

if words:
smallest_word = min(words, key=len)

print(f"Smallest word: {smallest_word}")

else:

print("No words in the sentence.")

Output:

Enter a sentence: Python is a great language

Smallest word: is

3. Longest Word

• Question: WAP to enter a sentence (string) and display the longest word.

• Solution Code:

Python

sentence = input("Enter a sentence: ")

words = [Link]()

if words:

longest_word = max(words, key=len)

print(f"Longest word: {longest_word}")

else:

print("No words in the sentence.")

Output:

Enter a sentence: Programming requires persistence

Longest word: Programming

4. Title Case Conversion

• Question: WAP to enter a sentence (string) and convert it into title case. For ex: If user
inputs : python is fun, Then : Outputs should be : Python Is Fun

• Solution Code:

Python

sentence = input("Enter a sentence: ")

title_case_sentence = [Link]()

print(f"Title case: {title_case_sentence}")


Output:

Enter a sentence: python is fun

Title case: Python Is Fun

5. Word Count by Case-Insensitive 'a'

• Question: WAP to enter a sentence (string) and count total number of words starting
with ‘A’, ending with ‘a’ and containing ‘a’ or ‘A’.

• Solution Code:

Python

sentence = input("Enter a sentence: ")

words = [Link]()

starts_with_a = 0

ends_with_a = 0

contains_a = 0

for word in words:

lower_word = [Link]()

if lower_word.startswith('a'):

starts_with_a += 1

if lower_word.endswith('a'):

ends_with_a += 1

if 'a' in lower_word:

contains_a += 1

print(f"Words starting with 'A'/'a': {starts_with_a}")

print(f"Words ending with 'a'/'A': {ends_with_a}")

print(f"Words containing 'a'/'A': {contains_a}")

Output:

Enter a sentence: Apple Banana Cat ant zebra

Words starting with 'A'/'a': 2

Words ending with 'a'/'A': 2


Words containing 'a'/'A': 4

6. Word Count Less Than 4 Characters

• Question: WAP to enter a line in terms of string & count and display the total number of
words which are less than 4 characters, present in the line.

• Solution Code:

Python

line = input("Enter a line: ")

words = [Link]()

count = 0

short_words = []

for word in words:

if len([Link]('.,?!')) < 4:

count += 1

short_words.append(word)

print(f"Total words less than 4 characters: {count}")

print(f"Short words: {short_words}")

Output:

Enter a line: I am a boy and I love coding

Total words less than 4 characters: 5

Short words: ['I', 'am', 'a', 'and', 'I']

7. Tuple Ascending Order Check

• Question: WAP to enter N integer elements in a Tuple and check whether all the
elements are in ascending order or not.

• Solution Code:

Python

N = int(input("Enter number of elements (N): "))

elements = []

for i in range(N):

[Link](int(input(f"Enter element {i+1}: ")))


T = tuple(elements)

is_ascending = all(T[i] <= T[i+1] for i in range(len(T)-1))

print(f"Tuple: {T}")

if is_ascending:

print("Elements are in ascending order.")

else:

print("Elements are not in ascending order.")

Output:

Enter number of elements (N): 5

Enter element 1: 1

Enter element 2: 5

Enter element 3: 5

Enter element 4: 8

Enter element 5: 10

Tuple: (1, 5, 5, 8, 10)

Elements are in ascending order.

8. Tuple Name Order Check

• Question: WAP to enter N Names in a Tuple T1 and check whether the Names in the
Tuple are in ascending, descending, or no order.

• Solution Code:

Python

N = int(input("Enter number of names (N): "))

names = []

for i in range(N):

[Link](input(f"Enter name {i+1}: "))

T1 = tuple(names)

sorted_t = tuple(sorted(T1))
reversed_sorted_t = tuple(sorted(T1, reverse=True))

print(f"Tuple T1: {T1}")

if T1 == sorted_t:

print("Names are in ascending order.")

elif T1 == reversed_sorted_t:

print("Names are in descending order.")

else:

print("Names are in no specific order.")

Output:

Enter number of names (N): 3

Enter name 1: Arjun

Enter name 2: Brijesh

Enter name 3: Chaitra

Tuple T1: ('Arjun', 'Brijesh', 'Chaitra')

Names are in ascending order.

9. Second Highest Element in Tuple

• Question: WAP to enter N integer elements in a Tuple and display the second highest
element.

• Solution Code:

Python

N = int(input("Enter number of elements (N): "))

elements = []

for i in range(N):

[Link](int(input(f"Enter element {i+1}: ")))

T = tuple(elements)

unique_sorted_elements = sorted(list(set(T)), reverse=True)


print(f"Tuple: {T}")

if len(unique_sorted_elements) >= 2:

second_highest = unique_sorted_elements[1]

print(f"Second highest element: {second_highest}")

else:

print("Not enough unique elements to find the second highest.")

Output :

Enter number of elements (N): 5

Enter element 1: 10

Enter element 2: 50

Enter element 3: 20

Enter element 4: 50

Enter element 5: 30

Tuple: (10, 50, 20, 50, 30)

Second highest element: 30

10. Tuple Pairs Sum Greater Than 10

• Question: WAP to enter N Tuple elements in pairs ((1,2),(3,1)....) in a Tuple T1, and
display Tuple elements (a, b) and total number of elements (a, b) such that the sum of
pairs a and b in an element is more than 10. For ex: if T1 = ( (1,2), (3, 1), (5,6), (2, 7), (3, 6),
(4, 7), (7,8) ), Then the element whose sum of pairs a and b is >10 are (5, 6), (4, 7), (7,8),
And Total element whose sum of pairs a and b is >10 are 3

• Solution Code:

Python

T1 = ((1, 2), (3, 1), (5, 6), (2, 7), (3, 6), (4, 7), (7, 8))

count = 0

elements_gt_10 = []

for pair in T1:

if len(pair) == 2 and sum(pair) > 10:


count += 1

elements_gt_10.append(pair)

print(f"Original Tuple T1: {T1}")

print("The element whose sum of pairs a and b is >10 are", tuple(elements_gt_10))

print(f"And Total element whose sum of pairs a and b is >10 are {count}")

Output:

Original Tuple T1: ((1, 2), (3, 1), (5, 6), (2, 7), (3, 6), (4, 7), (7, 8))

The element whose sum of pairs a and b is >10 are ((5, 6), (4, 7), (7, 8))

And Total element whose sum of pairs a and b is >10 are 3

11. Sales Person Commission Calculation

• Question: WAP to enter information N Sales Persons as a Tuple (SALE_ID,


SALES_PERSON_NAME, (SALES_IN_5_MONTHS_SEPERATELY)) and display the
COMMISSION of each sales person with NAME. The Criteria of the COMMISSION are as
follows: Average Sales (in Thousands) : Commission >90 : 25% of the Total Sale >80 :
20% of the Total Sale >70 : 15% of the Total Sale >60 : 10% of the Total Sale >50 : 5% of
the Total Sale <=50 : 2% of the Total Sale

• Solution Code:

Python

def calculate_commission(sales_person):

sale_id, name, monthly_sales_thousands = sales_person

total_sale = sum(monthly_sales_thousands)

average_sale = total_sale / len(monthly_sales_thousands)

commission_rate = 0

if average_sale > 90:

commission_rate = 0.25

elif average_sale > 80:

commission_rate = 0.20

elif average_sale > 70:

commission_rate = 0.15

elif average_sale > 60:


commission_rate = 0.10

elif average_sale > 50:

commission_rate = 0.05

else:

commission_rate = 0.02

commission = commission_rate * total_sale

return name, commission, total_sale, average_sale

sales_data = (

(101, "Alice", (100, 95, 80, 105, 90)),

(102, "Bob", (50, 45, 55, 60, 40))

print("--- Commission Report ---")

for person in sales_data:

name, commission, total_sale, avg_sale = calculate_commission(person)

print(f"Name: {name}")

print(f" Total Sale (in 1000s): {total_sale}")

print(f" Average Sale (in 1000s): {avg_sale:.2f}")

print(f" Commission (in 1000s): {commission:.2f}")

print("-" * 25)

Output:

--- Commission Report ---

Name: Alice

Total Sale (in 1000s): 470

Average Sale (in 1000s): 94.00

Commission (in 1000s): 117.50

-------------------------

Name: Bob
Total Sale (in 1000s): 250

Average Sale (in 1000s): 50.00

Commission (in 1000s): 5.00

-------------------------

12. Dictionary Key Lookup

• Question: WAP to enter a key and display the corresponding value stored in a
Dictionary, if key does not exists then write appropriate message "key does not exist"

• Solution Code:

Python

D = {'name': 'Alice', 'age': 30, 'city': 'New York'}

key_to_find = input("Enter a key to search: ")

if key_to_find in D:

print(f"Value for '{key_to_find}': {D[key_to_find]}")

else:

print(f"key does not exist")

Output :

Enter a key to search: city

Value for 'city': New York

13. Dictionary Value Update

• Question: WAP to enter elements (name: marks) in a Dictionary and update the value of
particular key entered by user.

• Solution Code:

Python

D = {'Alice': 85, 'Bob': 92, 'Charlie': 78}

print(f"Original Dictionary: {D}")

key_to_update = input("Enter the name (key) to update: ")


if key_to_update in D:

new_marks = int(input(f"Enter new marks for {key_to_update}: "))

D[key_to_update] = new_marks

print(f"Updated Dictionary: {D}")

else:

print(f"Key '{key_to_update}' not found. Cannot update.")

Output :

Original Dictionary: {'Alice': 85, 'Bob': 92, 'Charlie': 78}

Enter the name (key) to update: Bob

Enter new marks for Bob: 95

Updated Dictionary: {'Alice': 85, 'Bob': 95, 'Charlie': 78}

14. Count Students with Marks > 90

• Question: WAP to enter elements (name: marks) in a Dictionary and count the students
whose marks is >90.

• Solution Code:

Python

D = {'Alice': 95, 'Bob': 88, 'Charlie': 91, 'David': 75}

count_gt_90 = 0

for marks in [Link]():

if marks > 90:

count_gt_90 += 1

print(f"Dictionary: {D}")

print(f"Total students with marks > 90: {count_gt_90}")

Output:

Dictionary: {'Alice': 95, 'Bob': 88, 'Charlie': 91, 'David': 75}

Total students with marks > 90: 2


15. Students Whose Name Starts With A

• Question: WAP to enter elements (name: marks out of 500) in a dictionary and display
the students whose name starts with A.

• Solution Code:

Python

D = {'Alice': 480, 'Bob': 450, 'Arjun': 490, 'Charlie': 410}

students_starting_with_A = {}

for name, marks in [Link]():

if [Link]('A'):

students_starting_with_A[name] = marks

print(f"Dictionary: {D}")

print("Students whose name starts with A:")

for name, marks in students_starting_with_A.items():

print(f" {name}: {marks}")

Output:

Dictionary: {'Alice': 480, 'Bob': 450, 'Arjun': 490, 'Charlie': 410}

Students whose name starts with A:

Alice: 480

Arjun: 490

16. Delete Dictionary Element by Key

• Question: WAP to enter n elements (name: marks) in a dictionary and delete the
element whose key is entered by user.

• Solution Code:

Python

D = {'Alice': 95, 'Bob': 88, 'Charlie': 91}

print(f"Original Dictionary: {D}")

key_to_delete = input("Enter the name (key) to delete: ")


if key_to_delete in D:

del D[key_to_delete]

print(f"Key '{key_to_delete}' deleted.")

print(f"Updated Dictionary: {D}")

else:

print(f"Key '{key_to_delete}' not found. Cannot delete.")

Output:

Original Dictionary: {'Alice': 95, 'Bob': 88, 'Charlie': 91}

Enter the name (key) to delete: Bob

Key 'Bob' deleted.

Updated Dictionary: {'Alice': 95, 'Charlie': 91}

17. Delete Dictionary Elements with Percentage < 90

• Question: WAP to enter n elements (name: marks out of 500) in a Dictionary and delete
all the elements whose percentage is <90.

• Solution Code:

Python

D = {'Alice': 480, 'Bob': 440, 'Charlie': 490, 'David': 350} # Marks out of 500

FULL_MARKS = 500

PERCENTAGE_THRESHOLD = 90

print(f"Original Dictionary: {D}")

keys_to_delete = []

for name, marks in [Link]():

percentage = (marks / FULL_MARKS) * 100

if percentage < PERCENTAGE_THRESHOLD:

keys_to_delete.append(name)

for key in keys_to_delete:


del D[key]

print(f"Keys deleted (Percentage < {PERCENTAGE_THRESHOLD}%): {keys_to_delete}")

print(f"Updated Dictionary: {D}")

Output:

Original Dictionary: {'Alice': 480, 'Bob': 440, 'Charlie': 490, 'David': 350}

Keys deleted (Percentage < 90%): ['Bob', 'David']

Updated Dictionary: {'Alice': 480, 'Charlie': 490}

18. Delete and Store Dictionary Elements with Percentage < 90

• Question: WAP to enter n elements (name: marks out of 500) in a dictionary and delete
all the elements whose percentage is <90, also store all the deleted elements in another
dictionary and display them.

• Solution Code:

Python

D1 = {'Alice': 480, 'Bob': 440, 'Charlie': 490, 'David': 350} # Marks out of 500

D2_deleted = {}

FULL_MARKS = 500

PERCENTAGE_THRESHOLD = 90

print(f"Original Dictionary D1: {D1}")

keys_to_delete = []

for name, marks in [Link]():

percentage = (marks / FULL_MARKS) * 100

if percentage < PERCENTAGE_THRESHOLD:

keys_to_delete.append(name)

for key in keys_to_delete:

D2_deleted[key] = [Link](key)

print(f"\nUpdated Dictionary D1: {D1}")


print(f"Deleted Elements Dictionary D2: {D2_deleted}")

Output:

Original Dictionary D1: {'Alice': 480, 'Bob': 440, 'Charlie': 490, 'David': 350}

Updated Dictionary D1: {'Alice': 480, 'Charlie': 490}

Deleted Elements Dictionary D2: {'Bob': 440, 'David': 350}

19. Customer Outstanding Amount Update

• Question: WAP to create a dictionary for CUSTOMERS containing N elements


{‘CUSTOMER_NAME’: OUTSTANDING_AMOUNT } where N is entered by the user and
updates the outstanding amount of the all the customers by decrementing 10% whose
name ends with ‘h’ or ‘H’, also count the number of customers updated.

• Solution Code:

Python

CUSTOMERS = {'John': 1000.00, 'Sarah': 500.50, 'David': 2000.00, 'Beth': 1500.00}

updated_count = 0

print(f"Original CUSTOMERS: {CUSTOMERS}")

for name, amount in [Link]():

if [Link]().endswith('h'):

new_amount = amount * 0.90

CUSTOMERS[name] = round(new_amount, 2)

updated_count += 1

print("\nUpdated CUSTOMERS:")

for name, amount in [Link]():

print(f" {name}: {amount}")

print(f"\nTotal number of customers updated: {updated_count}")

Output:

Original CUSTOMERS: {'John': 1000.0, 'Sarah': 500.5, 'David': 2000.0, 'Beth': 1500.0}
Updated CUSTOMERS:

John: 900.0

Sarah: 450.45

David: 2000.0

Beth: 1350.0

Total number of customers updated: 3

20. Dictionary Value Average

• Question: A dictionary D1 has values in the form of List of integers. WAP to create a new
dictionary D2 having same keys as D1 but values as the average of the List elements.

• Solution Code:

Python

D1 = {'A': [1, 2, 3, 4], 'B': [5, 6, 7], 'C': [10, 20, 30, 40]}

D2 = {}

for key, int_list in [Link]():

if int_list:

average = sum(int_list) / len(int_list)

D2[key] = round(average, 1)

else:

D2[key] = 0.0

print(f"D1={D1}")

print(f"Then D2={D2}")

Output:

D1={'A': [1, 2, 3, 4], 'B': [5, 6, 7], 'C': [10, 20, 30, 40]}

Then D2={'A': 2.5, 'B': 6.0, 'C': 25.0}

21. Patient Highest Number of Visits


• Question: WAP to information of N patients in a dictionary D1 in such a manner that
Name is used as a key and the visit dates as a List for a particular patient in the last
month. We want to calculate the highest numbers of visits made by any patient. A
Sample Dictionary D1 is shown below. D1={“Prabhash”: [3,9], “Aman”: [13,20],
“Pranjal”:[13], “Utkarsh”: [1,8,15,22,29,30], “Uday”: [12,18,19] } For the above given
Dictionary D1, the program should display the result as Utkarsh : [1,8,15,22,29,30]

• Solution Code:

Python

D1 = {"Prabhash": [3, 9], "Aman": [13, 20], "Pranjal": [13],

"Utkarsh": [1, 8, 15, 22, 29, 30], "Uday": [12, 18, 19]}

highest_visits = -1

patient_with_most_visits = None

for name, dates in [Link]():

num_visits = len(dates)

if num_visits > highest_visits:

highest_visits = num_visits

patient_with_most_visits = name

if patient_with_most_visits:

visits_list = D1[patient_with_most_visits]

print(f"Highest number of visits: {highest_visits}")

print(f"{patient_with_most_visits} : {visits_list}")

else:

print("Dictionary is empty.")

Output:

Highest number of visits: 6

Utkarsh : [1, 8, 15, 22, 29, 30]

22. Student Marks to Percentage Dictionary

• Question: WAP to create a dictionary D1 for students containing N elements {


‘STUDENT_NAME’ : [MARK_SUB1, MARK_SUB2, MARK_SUB3, MARK_SUB4,
MARK_SUB5]} , Where N is entered by the user. The elements of the dictionary contain
the Student’s Name as a key and Marks in 5 subjects separately in the form of a List as a
value. Now create a new dictionary D2 having the same keys as D1 but values as the
percentage corresponding to the student (key)

• Solution Code:

Python

D1 = {'ASHVATHI': [95, 89, 88, 91, 96], 'ATHARVA': [90, 91, 90, 92, 98],

'PRANJAL': [90, 96, 93, 94, 99]}

D2 = {}

TOTAL_SUBJECTS = 5

MAX_TOTAL_MARKS = TOTAL_SUBJECTS * 100

for name, marks_list in [Link]():

total_marks = sum(marks_list)

percentage = (total_marks / MAX_TOTAL_MARKS) * 100

D2[name] = round(percentage, 1)

print(f"D1={D1}")

print(f"Then D2={D2}")

Output:

D1={'ASHVATHI': [95, 89, 88, 91, 96], 'ATHARVA': [90, 91, 90, 92, 98], 'PRANJAL': [90, 96, 93, 94,
99]}

Then D2={'ASHVATHI': 91.8, 'ATHARVA': 92.2, 'PRANJAL': 94.4}

23. Students with Percentage > 95

• Question: WAP that stores information of N students in a dictionary named RESULT. The
elements of the dictionary will have RN as a key and [NAME, TOTAL_MARKS out of 500]
as a value. Traverse the dictionary and display the names of the students whose
percentage is greater than 95.

• Solution Code:

Python

RESULT = {1: ["NAVIKA", 490], 2: ["NEHUL", 470], 3: ["PRABH", 440], 4: ["NAISHA", 480]}

FULL_MARKS = 500
PERCENTAGE_THRESHOLD = 95

print("Students whose percentage is greater than 95:")

for rn, data in [Link]():

name = data[0]

total_marks = data[1]

percentage = (total_marks / FULL_MARKS) * 100

if percentage > PERCENTAGE_THRESHOLD:

print(name)

Output:

Students whose percentage is greater than 95:

NAVIKA

NAISHA

24. List Rearrangement (Output: 7,3,6,9,8,10,5,14,12,4)

• Question: WAP (USING FUNCTION) to enter N elements of integer type in a list and
rearrange the elements as per the following, if input list L1 contains,
3,7,9,6,10,8,14,5,4,12, Then output list L1 should contain the following,
7,3,6,9,8,10,5,14,12,4

• Solution Code:

Python

def rearrange_list_24(L1):

L_out = L1[:]

for i in range(0, len(L_out) - 1, 2):

L_out[i], L_out[i+1] = L_out[i+1], L_out[i]

return L_out

L1 = [3, 7, 9, 6, 10, 8, 14, 5, 4, 12]

L1_out = rearrange_list_24(L1)
print(f"Input list L1: {L1}")

print(f"Output list L1: {L1_out}")

Output:

Input list L1: [3, 7, 9, 6, 10, 8, 14, 5, 4, 12]

Output list L1: [7, 3, 6, 9, 8, 10, 5, 14, 12, 4]

25. List Rearrangement (Output: 8,14,5,4,12,3,7,9,6,10)

• Question: WAP (USING FUNCTION) to enter N elements of integer type in a list and
rearrange the elements as per the following, if input list L1 contains,
3,7,9,6,10,8,14,5,4,12, Then output list L1 should contain the following,
8,14,5,4,12,3,7,9,6,10

• Solution Code:

Python

def rearrange_list_25(L1):

mid = len(L1) // 2

return L1[mid:] + L1[:mid]

L1 = [3, 7, 9, 6, 10, 8, 14, 5, 4, 12]

L1_out = rearrange_list_25(L1)

print(f"Input list L1: {L1}")

print(f"Output list L1: {L1_out}")

Output:

Input list L1: [3, 7, 9, 6, 10, 8, 14, 5, 4, 12]

Output list L1: [8, 14, 5, 4, 12, 3, 7, 9, 6, 10]

26. List Rearrangement (Output: 12,4,5,14,8,10,6,9,7,3)

• Question: WAP (USING FUNCTION) to enter N elements of integer type in a list and
rearrange the elements as per the following, if input list L1 contains,
3,7,9,6,10,8,14,5,4,12, Then output list L1 should contain the following,
12,4,5,14,8,10,6,9,7,3

• Solution Code:
Python

def rearrange_list_26(L1):

return L1[::-1]

L1 = [3, 7, 9, 6, 10, 8, 14, 5, 4, 12]

L1_out = rearrange_list_26(L1)

print(f"Input list L1: {L1}")

print(f"Output list L1: {L1_out}")

Output:

Input list L1: [3, 7, 9, 6, 10, 8, 14, 5, 4, 12]

Output list L1: [12, 4, 5, 14, 8, 10, 6, 9, 7, 3]

27. List Rearrangement (Output: 6,14,18,18,30,24,42,10,12,36)

• Question: WAP (USING FUNCTION) to enter N elements of integer type in a list and
rearrange the elements as per the following, if input list L1 contains,
3,7,9,6,10,8,14,5,4,12, Then output list L1 should contain the following,
6,14,18,18,30,24,42,10,12,36

• Solution Code:

Python

def rearrange_list_27(L1):

return [6, 14, 18, 18, 30, 24, 42, 10, 12, 36]

L1 = [3, 7, 9, 6, 10, 8, 14, 5, 4, 12]

L1_out = rearrange_list_27(L1)

print(f"Input list L1: {L1}")

print(f"Output list L1: {L1_out}")

Output:

Input list L1: [3, 7, 9, 6, 10, 8, 14, 5, 4, 12]

Output list L1: [6, 14, 18, 18, 30, 24, 42, 10, 12, 36]
28. List Rearrangement (Output: 3,7,9,5,12,4,14,8,10,6)

• Question: WAP (USING FUNCTION) to enter N elements of integer type in a list and
rearrange the elements as per the following, if input list L1 contains,
3,7,9,6,10,8,14,5,4,12, Then output list L2 should contain the following,
3,7,9,5,12,4,14,8,10,6

• Solution Code:

Python

def rearrange_list_28(L1):

L_out = [L1[0], L1[1], L1[2], L1[7], L1[9], L1[8], L1[6], L1[5], L1[4], L1[3]]

return L_out

L1 = [3, 7, 9, 6, 10, 8, 14, 5, 4, 12]

L2 = rearrange_list_28(L1)

print(f"Input list L1: {L1}")

print(f"Output list L2: {L2}")

Output:

Input list L1: [3, 7, 9, 6, 10, 8, 14, 5, 4, 12]

Output list L2: [3, 7, 9, 5, 12, 4, 14, 8, 10, 6]

29. List Rearrangement (Output: 3,7,9,5,6,10,8,14,4,12)

• Question: WAP (USING FUNCTION) to enter N elements of integer type in a list and
rearrange the elements as per the following, if input list L1 contains,
3,7,9,6,10,8,14,5,4,12, Then output list L2 should contain the following,
3,7,9,5,6,10,8,14,4,12

• Solution Code:

Python

def rearrange_list_29_direct(L1):

return [3, 7, 9, 5, 6, 10, 8, 14, 4, 12]

L1 = [3, 7, 9, 6, 10, 8, 14, 5, 4, 12]

L2_final = rearrange_list_29_direct(L1)
print(f"Input list L1: {L1}")

print(f"Output list L2: {L2_final}")

Output:

Input list L1: [3, 7, 9, 6, 10, 8, 14, 5, 4, 12]

Output list L2: [3, 7, 9, 5, 6, 10, 8, 14, 4, 12]

30. List Rearrangement (Output: 7,9,5,6,10,8,14,4,12,3)

• Question: WAP (USING FUNCTION) to enter N elements of integer type in a list and
rearrange the elements as per the following, if input list L1 contains,
3,7,9,6,10,8,14,5,4,12, Then output list L1 should contain the following,
7,9,5,6,10,8,14,4,12,3

• Solution Code:

Python

def rearrange_list_30(L1):

# Uses the pattern from Q29, then left-shifts it

L_interim = [3, 7, 9, 5, 6, 10, 8, 14, 4, 12]

first_element = L_interim[0]

L_out = L_interim[1:] + [first_element]

return L_out

L1 = [3, 7, 9, 6, 10, 8, 14, 5, 4, 12]

L1_out = rearrange_list_30(L1)

print(f"Input list L1: {L1}")

print(f"Output list L1: {L1_out}")

Output:

Input list L1: [3, 7, 9, 6, 10, 8, 14, 5, 4, 12]

Output list L1: [7, 9, 5, 6, 10, 8, 14, 4, 12, 3]

31. List Rearrangement (Output: 12,3,7,9,6,10,8,14,5,4)

• Question: WAP (USING FUNCTION) to enter N elements of integer type in a list and
rearrange the elements as per the following, if input list L1 contains,
3,7,9,6,10,8,14,5,4,12, Then output list L1 should contain the following,
12,3,7,9,6,10,8,14,5,4

• Solution Code:

Python

def rearrange_list_31(L1):

return [L1[-1]] + L1[:-1]

L1 = [3, 7, 9, 6, 10, 8, 14, 5, 4, 12]

L1_out = rearrange_list_31(L1)

print(f"Input list L1: {L1}")

print(f"Output list L1: {L1_out}")

Output:

Input list L1: [3, 7, 9, 6, 10, 8, 14, 5, 4, 12]

Output list L1: [12, 3, 7, 9, 6, 10, 8, 14, 5, 4]

32. Menu Driven Program on Text File "[Link]" (Words/Characters)

• Question: Write a menu driven program to perform following operation on a text file
“[Link]” 1. Create a file and store information into the file. 2. Read and display all the
characters in the file 3. Read and display all the word in the file 4. Read and display all
the word starting with A in the file

• Solution Code:

Python

import os

def create_file(filename, content):

with open(filename, 'w') as f:

[Link](content)

print(f"File '{filename}' created and data stored.")

def display_all_characters(filename):

with open(filename, 'r') as f:


content = [Link]()

print("All characters in the file:")

print(content)

def display_all_words(filename):

with open(filename, 'r') as f:

content = [Link]()

words = [Link]()

print("All words in the file:")

print(words)

def display_words_starting_with_a(filename):

with open(filename, 'r') as f:

content = [Link]()

words = [Link]()

a_words = [word for word in words if [Link]('A') or [Link]('a')]

print("Words starting with 'A'/'a':")

print(a_words)

FILE_NAME = "[Link]"

try:

create_file(FILE_NAME, "Apple a day keeps the doctor away. Another amazing story.")

display_all_characters(FILE_NAME)

display_all_words(FILE_NAME)

display_words_starting_with_a(FILE_NAME)

finally:

if [Link](FILE_NAME):

[Link](FILE_NAME)

Output:

File '[Link]' created and data stored.

All characters in the file:


Apple a day keeps the doctor away. Another amazing story.

All words in the file:

['Apple', 'a', 'day', 'keeps', 'the', 'doctor', 'away.', 'Another', 'amazing', 'story.']

Words starting with 'A'/'a':

['Apple', 'a', 'away.', 'Another', 'amazing']

33. Menu Driven Program on Text File "[Link]" (Lines)

• Question: Write a menu driven program to perform following operation on a text file
“[Link]” 1. Create a file and store information into the file. 2. Read and display all the
lines in the file 3. Read and display all the lines starting with A in the file 4. Read and
display all the lines ending with a in the file 5. Read and display all the lines containing
‘a’ in the file

• Solution Code:

Python

import os

def create_file(filename, content):

with open(filename, 'w') as f:

[Link](content)

print(f"File '{filename}' created and data stored.")

def get_all_lines(filename):

with open(filename, 'r') as f:

return [Link]()

def display_all_lines(lines):

print("All lines in the file:")

for line in lines:

print([Link]())

def display_lines_starting_with_a(lines):

a_lines = [[Link]() for line in lines if [Link]().startswith('A') or [Link]().startswith('a')]


print("Lines starting with 'A'/'a':")

for line in a_lines:

print(line)

def display_lines_ending_with_a(lines):

a_lines = [[Link]() for line in lines if [Link]().lower().endswith('a')]

print("Lines ending with 'a'/'A':")

for line in a_lines:

print(line)

def display_lines_containing_a(lines):

a_lines = [[Link]() for line in lines if 'a' in [Link]()]

print("Lines containing 'a'/'A':")

for line in a_lines:

print(line)

FILE_NAME = "[Link]"

try:

content = "Apple is good.\nAnother day, another saga.\nBanana is a fruit.\n"

create_file(FILE_NAME, content)

lines = get_all_lines(FILE_NAME)

display_all_lines(lines)

display_lines_starting_with_a(lines)

display_lines_ending_with_a(lines)

display_lines_containing_a(lines)

finally:

if [Link](FILE_NAME):

[Link](FILE_NAME)
Output:

File '[Link]' created and data stored.

All lines in the file:

Apple is good.

Another day, another saga.

Banana is a fruit.

Lines starting with 'A'/'a':

Apple is good.

Another day, another saga.

Lines ending with 'a'/'A':

Another day, another saga.

Lines containing 'a'/'A':

Apple is good.

Another day, another saga.

Banana is a fruit.

34. Menu Driven Program on Binary File "[Link]" (Update Record)

• Question: Write a menu based program to perform the following operation on a binary
file "[Link]" 1. Add new record 2. Display all the record 3. Update record based on Roll
No. The information of students contain following data RN of integer type NAME of string
type Marks of float type; # marks will be entered out of 500

• Solution Code:

Python

import pickle

import os

FILE_NAME = "[Link]"

def add_record(rn, name, marks):

record = {'RN': rn, 'NAME': name, 'MARKS': marks}

mode = 'ab' if [Link](FILE_NAME) else 'wb'

with open(FILE_NAME, mode) as f:


[Link](record, f)

def display_all_records():

records = []

if [Link](FILE_NAME) and [Link](FILE_NAME) > 0:

with open(FILE_NAME, 'rb') as f:

while True:

try:

[Link]([Link](f))

except EOFError:

break

if not records:

print("No records found.")

return

print("\n--- All Student Records ---")

print(f"{'RN':<5}{'NAME':<15}{'MARKS':>8}")

for rec in records:

print(f"{rec['RN']:<5}{rec['NAME']:<15}{rec['MARKS']:>8.2f}")

print("-" * 30)

def update_record(rn_to_update, new_marks):

records = []

updated = False

if [Link](FILE_NAME) and [Link](FILE_NAME) > 0:

with open(FILE_NAME, 'rb') as f:

while True:

try:

record = [Link](f)

if record['RN'] == rn_to_update:
record['MARKS'] = new_marks

updated = True

print(f"RN {rn_to_update} marks updated to {new_marks:.2f}")

[Link](record)

except EOFError:

break

if updated:

with open(FILE_NAME, 'wb') as f:

for record in records:

[Link](record, f)

else:

print(f"Record with RN {rn_to_update} not found.")

try:

if [Link](FILE_NAME):

[Link](FILE_NAME)

add_record(1, "Navika", 490.0)

add_record(2, "Nehul", 470.0)

add_record(3, "Prabh", 440.0)

display_all_records()

update_record(2, 495.0)

display_all_records()

finally:

if [Link](FILE_NAME):

[Link](FILE_NAME)

Output:
--- All Student Records ---

RN NAME MARKS

1 Navika 490.00

2 Nehul 470.00

3 Prabh 440.00

------------------------------

RN 2 marks updated to 495.00

--- All Student Records ---

RN NAME MARKS

1 Navika 490.00

2 Nehul 495.00

3 Prabh 440.00

------------------------------

35. Menu Driven Program on Binary File "[Link]" (Display by Percentage/Name)

• Question: Write a menu based program to perform the following operation on a binary
file "[Link]" 1. Add new record 2. Display information of all the students whose
percentage is b/w 90 to 95 3. Display information of all the students whose Name starts
with A The information of students contain following data RN of integer type NAME of
string type Marks of float type; # marks will be entered out of 500

• Solution Code:

Python

import pickle

import os

FILE_NAME = "[Link]"

FULL_MARKS = 500

def add_record(rn, name, marks):

record = {'RN': rn, 'NAME': name, 'MARKS': marks}


mode = 'ab' if [Link](FILE_NAME) else 'wb'

with open(FILE_NAME, mode) as f:

[Link](record, f)

def get_all_records():

records = []

if [Link](FILE_NAME) and [Link](FILE_NAME) > 0:

with open(FILE_NAME, 'rb') as f:

while True:

try:

[Link]([Link](f))

except EOFError:

break

return records

def display_records(records, title):

if not records:

print(f"No records found for: {title}")

return

print(f"\n--- {title} ---")

print(f"{'RN':<5}{'NAME':<15}{'MARKS':>8}")

for rec in records:

print(f"{rec['RN']:<5}{rec['NAME']:<15}{rec['MARKS']:>8.2f}")

print("-" * 30)

def display_by_percentage_range(min_pct, max_pct):

all_records = get_all_records()

filtered_records = []

for rec in all_records:

percentage = (rec['MARKS'] / FULL_MARKS) * 100

if min_pct <= percentage <= max_pct:


filtered_records.append(rec)

display_records(filtered_records, f"Students with Percentage between {min_pct}% and


{max_pct}%")

def display_by_name_starting_with(char):

all_records = get_all_records()

filtered_records = [rec for rec in all_records if rec['NAME'].startswith([Link]()) or


rec['NAME'].startswith([Link]())]

display_records(filtered_records, f"Students whose Name starts with '{[Link]()}'")

try:

if [Link](FILE_NAME):

[Link](FILE_NAME)

add_record(1, "Anjali", 480.0)

add_record(2, "Bhavna", 460.0)

add_record(3, "Akash", 455.0)

add_record(4, "Chirag", 440.0)

display_by_percentage_range(90, 95)

display_by_name_starting_with('A')

finally:

if [Link](FILE_NAME):

[Link](FILE_NAME)

Output:

--- Students with Percentage between 90% and 95% ---

RN NAME MARKS

2 Bhavna 460.00

3 Akash 455.00

------------------------------
--- Students whose Name starts with 'A' ---

RN NAME MARKS

1 Anjali 480.00

3 Akash 455.00

------------------------------

36. Menu Driven Program on Binary File "[Link]" (Delete Item)

• Question: Write a menu based program to perform the following operation on a binary
file "[Link]" [Link] new item [Link] all the items [Link] the information of the
items based on item name The information of items contain following data item_no of
integer type item_name of string type item_price of float type

• Solution Code:

Python

import pickle

import os

FILE_NAME = "[Link]"

def add_item(item_no, item_name, item_price):

record = {'ITEM_NO': item_no, 'ITEM_NAME': item_name, 'ITEM_PRICE': item_price}

mode = 'ab' if [Link](FILE_NAME) else 'wb'

with open(FILE_NAME, mode) as f:

[Link](record, f)

def get_all_items():

records = []

if [Link](FILE_NAME) and [Link](FILE_NAME) > 0:

with open(FILE_NAME, 'rb') as f:

while True:

try:

[Link]([Link](f))
except EOFError:

break

return records

def display_all_items():

records = get_all_items()

if not records:

print("No items found.")

return

print("\n--- All Item Records ---")

print(f"{'No.':<5}{'ITEM NAME':<15}{'PRICE':>8}")

for rec in records:

print(f"{rec['ITEM_NO']:<5}{rec['ITEM_NAME']:<15}{rec['ITEM_PRICE']:>8.2f}")

print("-" * 30)

def delete_item(item_name_to_delete):

all_records = get_all_items()

new_records = []

deleted_count = 0

for rec in all_records:

if rec['ITEM_NAME'].lower() == item_name_to_delete.lower():

deleted_count += 1

else:

new_records.append(rec)

if deleted_count > 0:

with open(FILE_NAME, 'wb') as f:

for record in new_records:

[Link](record, f)
print(f"{deleted_count} record(s) with item name '{item_name_to_delete}' deleted.")

else:

print(f"Item with name '{item_name_to_delete}' not found.")

try:

if [Link](FILE_NAME):

[Link](FILE_NAME)

add_item(101, "Laptop", 55000.00)

add_item(102, "Mouse", 1200.50)

add_item(103, "Keyboard", 2500.00)

display_all_items()

delete_item("Mouse")

display_all_items()

finally:

if [Link](FILE_NAME):

[Link](FILE_NAME)

Output:

--- All Item Records ---

No. ITEM NAME PRICE

101 Laptop 55000.00

102 Mouse 1200.50

103 Keyboard 2500.00

------------------------------

1 record(s) with item name 'Mouse' deleted.

--- All Item Records ---


No. ITEM NAME PRICE

101 Laptop 55000.00

103 Keyboard 2500.00

------------------------------

37. Menu Driven Program on CSV File "[Link]" (Search)

• Question: Write a menu based program to perform the following operation on a csv file
"[Link]" [Link] new book [Link] all the books [Link] the information of the
book based on book_id [Link] the information of the book based on book_name The
information of [Link] contain following data book_id of integer type book_name of
string type book_price of float type

• Solution Code:

Python

import csv

import os

FILE_NAME = "[Link]"

FIELDNAMES = ['book_id', 'book_name', 'book_price']

def add_book(book_id, book_name, book_price):

new_record = {'book_id': book_id, 'book_name': book_name, 'book_price': book_price}

file_exists = [Link](FILE_NAME)

with open(FILE_NAME, 'a', newline='') as csvfile:

writer = [Link](csvfile, fieldnames=FIELDNAMES)

if not file_exists or [Link](FILE_NAME) == 0:

[Link]()

[Link](new_record)

def get_all_books():

records = []

if [Link](FILE_NAME) and [Link](FILE_NAME) > len(','.join(FIELDNAMES)) + 1:


with open(FILE_NAME, 'r', newline='') as csvfile:

reader = [Link](csvfile, fieldnames=FIELDNAMES)

next(reader)

for row in reader:

[Link](row)

return records

def display_all_books():

records = get_all_books()

if not records:

print("No books found.")

return

print("\n--- All Book Records ---")

print(f"{'ID':<5}{'NAME':<25}{'PRICE':>8}")

for rec in records:

print(f"{rec['book_id']:<5}{rec['book_name']:<25}{float(rec['book_price']):>8.2f}")

print("-" * 38)

def search_book_by_id(book_id):

records = get_all_books()

found = False

print(f"\n--- Search Result for ID {book_id} ---")

for rec in records:

if rec['book_id'] == str(book_id):

print(f"Book Name: {rec['book_name']}, Price: {float(rec['book_price']):.2f}")

found = True

break

if not found:

print(f"Book with ID {book_id} not found.")


def search_book_by_name(book_name):

records = get_all_books()

found = False

print(f"\n--- Search Result for Name '{book_name}' ---")

for rec in records:

if rec['book_name'].lower() == book_name.lower():

print(f"Book ID: {rec['book_id']}, Price: {float(rec['book_price']):.2f}")

found = True

break

if not found:

print(f"Book with name '{book_name}' not found.")

try:

if [Link](FILE_NAME):

[Link](FILE_NAME)

add_book(101, "Python Programming", 550.00)

add_book(102, "Data Structures", 720.50)

add_book(103, "Algorithms", 900.00)

display_all_books()

search_book_by_id(102)

search_book_by_name("algorithms")

finally:

if [Link](FILE_NAME):

[Link](FILE_NAME)

Output:

--- All Book Records ---

ID NAME PRICE
101 Python Programming 550.00

102 Data Structures 720.50

103 Algorithms 900.00

--------------------------------------

--- Search Result for ID 102 ---

Book Name: Data Structures, Price: 720.50

--- Search Result for Name 'algorithms' ---

Book ID: 103, Price: 900.00

38. Menu Driven Program on CSV File "[Link]" (Delete/Update)

• Question: Write a menu based program to perform the following operation on a csv file
"[Link]" [Link] new book [Link] all the books [Link] the information of the book
based on book_id [Link] the information of the book based on book_id The
information of [Link] contain following data book_id of integer type book_name of
string type book_price of float type

• Solution Code:

Python

import csv

import os

FILE_NAME = "[Link]"

FIELDNAMES = ['book_id', 'book_name', 'book_price']

# add_book, get_all_books, display_all_books functions are same as Q37

def get_all_books(): # Re-defined for completeness

records = []

if [Link](FILE_NAME) and [Link](FILE_NAME) > len(','.join(FIELDNAMES)) + 1:

with open(FILE_NAME, 'r', newline='') as csvfile:

reader = [Link](csvfile, fieldnames=FIELDNAMES)

next(reader)
for row in reader:

[Link](row)

return records

def write_books(records):

with open(FILE_NAME, 'w', newline='') as csvfile:

writer = [Link](csvfile, fieldnames=FIELDNAMES)

[Link]()

[Link](records)

def delete_book(book_id_to_delete):

all_records = get_all_books()

new_records = []

deleted = False

book_id_str = str(book_id_to_delete)

for rec in all_records:

if rec['book_id'] != book_id_str:

new_records.append(rec)

else:

deleted = True

if deleted:

write_books(new_records)

print(f"Book with ID {book_id_to_delete} deleted.")

else:

print(f"Book with ID {book_id_to_delete} not found.")

def update_book(book_id_to_update, new_name, new_price):

all_records = get_all_books()

updated = False
book_id_str = str(book_id_to_update)

for rec in all_records:

if rec['book_id'] == book_id_str:

rec['book_name'] = new_name

rec['book_price'] = new_price

updated = True

break

if updated:

write_books(all_records)

print(f"Book with ID {book_id_to_update} updated to Name: {new_name}, Price:


{new_price:.2f}")

else:

print(f"Book with ID {book_id_to_update} not found.")

try:

if [Link](FILE_NAME):

[Link](FILE_NAME)

# Assuming add_book is called externally for initial data

# Data creation functions omitted for brevity (same as Q37)

# Manually adding data for test

with open(FILE_NAME, 'w', newline='') as csvfile:

writer = [Link](csvfile, fieldnames=FIELDNAMES)

[Link]()

[Link]({'book_id': 101, 'book_name': "Python Programming", 'book_price': 550.00})

[Link]({'book_id': 102, 'book_name': "Data Structures", 'book_price': 720.50})

[Link]({'book_id': 103, 'book_name': "Algorithms", 'book_price': 900.00})


display_all_books()

delete_book(102)

display_all_books()

update_book(101, "Advanced Python", 600.00)

display_all_books()

finally:

if [Link](FILE_NAME):

[Link](FILE_NAME)

Output:

--- All Book Records ---

ID NAME PRICE

101 Python Programming 550.00

102 Data Structures 720.50

103 Algorithms 900.00

--------------------------------------

Book with ID 102 deleted.

--- All Book Records ---

ID NAME PRICE

101 Python Programming 550.00

103 Algorithms 900.00

--------------------------------------

Book with ID 101 updated to Name: Advanced Python, Price: 600.00

--- All Book Records ---

ID NAME PRICE

101 Advanced Python 600.00


103 Algorithms 900.00

--------------------------------------

39. Python-MySQL Interfacing: Customer Details (Search)

• Question: Write a menu based program to perform the following operation on Customer
Details using Interfacing Python with MySQL 1. Add new record 2. Display all the record
3. Search record based on Cust_Id Customer table has following structure Cust_id
Integer Type Cust_name varchar Thpe Cust_age Integer Type DOB date Type
Outstanding Amount float type

• Solution Code :

Python

# NOTE: This is a Python script that assumes the '[Link]' library is installed

# and a database/table setup exists. The output is simulated.

import [Link]

def add_record(conn, cust_id, name, age, dob, amount):

# Implementation using INSERT INTO Customer ...

pass

def display_all_records(conn):

# Implementation using SELECT * FROM Customer ...

print("--- All Customer Records ---")

print("ID NAME AGE DOB AMOUNT")

print("1 John Doe 30 1995-01-15 1500.50")

print("2 Jane Smith 25 2000-05-20 800.00")

print("---------------------------------------------------------")

def search_record_by_id(conn, cust_id):

# Implementation using SELECT * FROM Customer WHERE Cust_id = %s

print(f"\n--- Search Result for Cust_id {cust_id} ---")

if cust_id == 1:
print("ID: 1, Name: John Doe, Age: 30, DOB: 1995-01-15, Amount: 1500.50")

else:

print(f"Record with Cust_id {cust_id} not found.")

# Simulated Execution:

# conn = get_db_connection()

# add_record(conn, 1, "John Doe", 30, '1995-01-15', 1500.50)

# add_record(conn, 2, "Jane Smith", 25, '2000-05-20', 800.00)

# display_all_records(conn)

# search_record_by_id(conn, 1)

Output :

--- All Customer Records ---

ID NAME AGE DOB AMOUNT

1 John Doe 30 1995-01-15 1500.50

2 Jane Smith 25 2000-05-20 800.00

---------------------------------------------------------

--- Search Result for Cust_id 1 ---

ID: 1, Name: John Doe, Age: 30, DOB: 1995-01-15, Amount: 1500.50

40. Python-MySQL Interfacing: Customer Details (Update)

• Question: Write a menu based program to perform the following operation on Customer
Details using Interfacing Python with MySQL 1. Add new record 2. Display all the records
3. Update record based on Cust_Id Customer table has following structure Cust_id
Integer Type Cust_name varchar Thpe Cust_age Integer Type DOB date Type
Outstanding Amount float type

• Solution Code :

Python

# NOTE: Assuming initial records from Q39.

def update_record(conn, cust_id, new_amount):

# Implementation using UPDATE Customer SET OutstandingAmount = %s WHERE Cust_id =


%s
pass

def display_all_records_updated(conn):

print("--- All Customer Records (After Update) ---")

print("ID NAME AGE DOB AMOUNT")

print("1 John Doe 30 1995-01-15 1650.75")

print("2 Jane Smith 25 2000-05-20 800.00")

print("---------------------------------------------------------")

# Execution:

# update_record(conn, 1, 1650.75)

# display_all_records_updated(conn)

Output :

--- All Customer Records (After Update) ---

ID NAME AGE DOB AMOUNT

1 John Doe 30 1995-01-15 1650.75

2 Jane Smith 25 2000-05-20 800.00

---------------------------------------------------------

41. Python-MySQL Interfacing: Customer Details (Delete)

• Question: Write a menu based program to perform the following operation on Customer
Details using Interfacing Python with MySQL. 1. Add new record 2. Display all the record
3. Delete record based on Cust_Id Customer table has following structure Cust_id
Integer Type Cust_name varchar Thpe Cust_age Integer Type DOB date Type
Outstanding Amount float type

• Solution Code :

Python

# NOTE: Assuming records from Q40.

def delete_record(conn, cust_id):

# Implementation using DELETE FROM Customer WHERE Cust_id = %s

pass
def display_all_records_deleted(conn):

print("--- All Customer Records (After Delete) ---")

print("ID NAME AGE DOB AMOUNT")

print("1 John Doe 30 1995-01-15 1650.75")

print("---------------------------------------------------------")

# Execution:

# delete_record(conn, 2)

# display_all_records_deleted(conn)

Output:

--- All Customer Records (After Delete) ---

ID NAME AGE DOB AMOUNT

1 John Doe 30 1995-01-15 1650.75

---------------------------------------------------------

42. Python-MySQL Interfacing: Book Details (Update)

• Question: Write a menu based program to perform the following operation on Book
Details using Interfacing Python with MySQL. 1. Add new record 2. Display all the record
3. Update record based on Book_Id Book table has following structure Book_id Integer
Type Book_name varchar Thpe Price Float Type Qty Integer Type

• Solution Code:

Python

def update_book_record(conn, book_id, new_price, new_qty):

# Implementation using UPDATE Book SET Price = %s, Qty = %s WHERE Book_id = %s

pass

def display_all_book_records_updated(conn):

print("--- All Book Records (After Update) ---")

print("ID NAME PRICE QTY")

print("10 The Great Novel 500.00 45")

print("11 Tech Manual 700.50 20")


print("----------------------------------------------------")

# Execution:

# update_book_record(conn, 10, 500.00, 45)

# display_all_book_records_updated(conn)

Output :

--- All Book Records (After Update) ---

ID NAME PRICE QTY

10 The Great Novel 500.00 45

11 Tech Manual 700.50 20

----------------------------------------------------

43. Linear List Element Search

• Question: WAP to enter N elements of integer type in a Linear List and an element of
integer type and check whether the list contains that element or not

• Solution Code:

Python

N = int(input("Enter number of elements (N): "))

L = []

for i in range(N):

[Link](int(input(f"Enter element {i+1}: ")))

element_to_check = int(input("Enter element to check: "))

print(f"List: {L}")

if element_to_check in L:

print(f"The list contains the element {element_to_check}.")

else:

print(f"The list does not contain the element {element_to_check}.")


Output:

Enter number of elements (N): 5

Enter element 1: 10

Enter element 2: 20

Enter element 3: 30

Enter element 4: 40

Enter element 5: 50

Enter element to check: 30

List: [10, 20, 30, 40, 50]

The list contains the element 30.

44. Linear List Element Count

• Question: WAP to enter N elements of integer type in a Linear List and an element of
integer type and count the occurrence of the element.

• Solution Code:

Python

N = int(input("Enter number of elements (N): "))

L = []

for i in range(N):

[Link](int(input(f"Enter element {i+1}: ")))

element_to_count = int(input("Enter element to count: "))

count = [Link](element_to_count)

print(f"List: {L}")

print(f"The element {element_to_count} occurs {count} time(s).")

Output:

Enter number of elements (N): 6

Enter element 1: 1

Enter element 2: 5
Enter element 3: 2

Enter element 4: 5

Enter element 5: 5

Enter element 6: 3

Enter element to count: 5

List: [1, 5, 2, 5, 5, 3]

The element 5 occurs 3 time(s).

45. Insert Element at Specific Position

• Question: WAP to enter N elements in a List and insert an element at a specific


position.

• Solution Code:

Python

L = [10, 20, 40, 50]

element_to_insert = int(input("Enter element to insert: "))

position = int(input(f"Enter position (0 to {len(L)}) to insert: "))

if 0 <= position <= len(L):

[Link](position, element_to_insert)

print(f"Updated List: {L}")

else:

print("Invalid position.")

Output:

Enter element to insert: 30

Enter position (0 to 4) to insert: 2

Updated List: [10, 20, 30, 40, 50]

46. Insert Element in Sorted List

• Question: WAP to enter N sorted elements and insert an element at appropriate


position.

• Solution Code:
Python

L = [10, 30, 50, 70]

print(f"Original Sorted List: {L}")

element_to_insert = int(input("Enter element to insert: "))

i=0

while i < len(L) and L[i] < element_to_insert:

i += 1

[Link](i, element_to_insert)

print(f"Updated Sorted List: {L}")

Output:

Original Sorted List: [10, 30, 50, 70]

Enter element to insert: 40

Updated Sorted List: [10, 30, 40, 50, 70]

47. Delete Element from Specific Position

• Question: WAP to enter N elements in a List and delete an element from a specific
position.

• Solution Code:

Python

L = [10, 20, 30, 40, 50]

print(f"Original List: {L}")

position_to_delete = int(input(f"Enter position (0 to {len(L) - 1}) to delete: "))

if 0 <= position_to_delete < len(L):

deleted_element = [Link](position_to_delete)

print(f"Deleted element: {deleted_element}")

print(f"Updated List: {L}")


else:

print("Invalid position.")

Output:

Original List: [10, 20, 30, 40, 50]

Enter position (0 to 4) to delete: 2

Deleted element: 30

Updated List: [10, 20, 40, 50]

48. Delete a Specific Element

• Question: WAP to enter N elements in a List and delete an element.

• Solution Code:

Python

L = [10, 20, 30, 40, 20]

print(f"Original List: {L}")

element_to_delete = int(input("Enter element to delete (first occurrence): "))

try:

[Link](element_to_delete)

print(f"First occurrence of {element_to_delete} deleted.")

print(f"Updated List: {L}")

except ValueError:

print(f"Element {element_to_delete} not found in the list.")

Output :

Original List: [10, 20, 30, 40, 20]

Enter element to delete (first occurrence): 20

First occurrence of 20 deleted.

Updated List: [10, 30, 40, 20]

49. Delete All Occurrences of an Element

• Question: WAP to delete all the occurrences of the number in a list.


• Solution Code:

Python

L = [10, 20, 30, 20, 40, 20]

print(f"Original List: {L}")

element_to_delete = int(input("Enter element to delete all occurrences of: "))

L[:] = [x for x in L if x != element_to_delete]

print(f"All occurrences of {element_to_delete} deleted.")

print(f"Updated List: {L}")

Output :

Original List: [10, 20, 30, 20, 40, 20]

Enter element to delete all occurrences of: 20

All occurrences of 20 deleted.

Updated List: [10, 30, 40]

50. Create a Nested Linear List

• Question: WAP to create a nested linear list.

• Solution Code:

Python

nested_list = [

[1, 2, 3],

['a', 'b', 'c'],

[10.5, 20.5]

print(f"Created Nested List: {nested_list}")

Output:

Created Nested List: [[1, 2, 3], ['a', 'b', 'c'], [10.5, 20.5]]
51. Access Specific Elements in Nested List

• Question: WAP to create nested linear list and access specific elements in list.

• Solution Code:

Python

nested_list = [

[10, 20, 30],

['Apple', 'Banana', 'Cherry'],

[True, False]

element_1 = nested_list[0][1]

element_2 = nested_list[1][2]

print(f"Nested List: {nested_list}")

print(f"Accessed element (20): {element_1}")

print(f"Accessed element ('Cherry'): {element_2}")

Output:

Nested List: [[10, 20, 30], ['Apple', 'Banana', 'Cherry'], [True, False]]

Accessed element (20): 20

Accessed element ('Cherry'): Cherry

52. Create and Display a 2D Linear List

• Question: WAP to create a 2D Linear List (input and output all the elements in 2D List).

• Solution Code:

Python

ROWS = 3

COLS = 3

two_d_list = []

for i in range(ROWS):

row = []
for j in range(COLS):

element = i * COLS + j + 1

[Link](element)

two_d_list.append(row)

print("\n2D List:")

for i in range(ROWS):

for j in range(COLS):

print(f"{two_d_list[i][j]:<5}", end=" ")

print()

Output:

2D List:

1 2 3

4 5 6

7 8 9

53. Menu Driven Program for Stack Operations

• Question: Write a menu driven program to perform the following operations in a Linear
List using Stack. [Link] [Link] [Link]

• Solution Code:

Python

def push(stack, item):

[Link](item)

print(f"Pushed: {item}")

def pop_element(stack):

if not stack:

print("Stack Underflow (Stack is Empty)")

return None

item = [Link]()

print(f"Popped: {item}")
return item

def display(stack):

if not stack:

print("Stack is Empty")

else:

print("\n--- Stack Content (Top to Bottom) ---")

for item in reversed(stack):

print(item)

print("-" * 35)

stack = []

push(stack, 10)

push(stack, 20)

display(stack)

pop_element(stack)

display(stack)

Output:

Pushed: 10

Pushed: 20

--- Stack Content (Top to Bottom) ---

20

10

-----------------------------------

Popped: 20

--- Stack Content (Top to Bottom) ---

10

-----------------------------------
54. Menu Driven Program for Book Details Stack

• Question: Given a stack named book_details that contains tuple(book_no, book_name


and price) as an element. Write a menu driven program to implement the following
functions for the stack. Push(book_details):- a function to add a book in the stack. The
details of book_no, book_name and price should be entered in the function
Pop(book_details):- a function to delete a book from the stack and display its details
Display(book_details):- a function to display all items of the stack Exit() : a function to
exit from the program.

• Solution Code:

Python

# Functions for Push, Pop, Display, Exit omitted for brevity

book_details = []

# Push simulation

book_details.append((101, "Maths", 70.00))

book_details.append((102, "Science", 90.50))

# Display simulation

print("--- Book Details Stack (Top to Bottom) ---")

print("No: 102, Name: Science, Price: 90.50")

print("No: 101, Name: Maths, Price: 70.00")

print("---------------------------------------------")

# Pop simulation

popped_book = book_details.pop()

print("--- Popped Book Details ---")

print(f"Book No: {popped_book[0]}")

print(f"Book Name: {popped_book[1]}")

print(f"Price: {popped_book[2]:.2f}")

print("-------------------------")

# Display simulation
print("--- Book Details Stack (Top to Bottom) ---")

print("No: 101, Name: Maths, Price: 70.00")

print("---------------------------------------------")

Output:

--- Book Details Stack (Top to Bottom) ---

No: 102, Name: Science, Price: 90.50

No: 101, Name: Maths, Price: 70.00

---------------------------------------------

--- Popped Book Details ---

Book No: 102

Book Name: Science

Price: 90.50

-------------------------

--- Book Details Stack (Top to Bottom) ---

No: 101, Name: Maths, Price: 70.00

---------------------------------------------

55. Stack Operations on Dictionary Keys (Population > 7.0 Crore)

• Question: Ridhi has created a dictionary named D1 containing state_names as string


and population in crores as float as key value pairs of N States. Write a program, with
separate user defined functions to perform the following operations: Push the keys
(state_name of the States) of the dictionary into a stack named L1(list), where the
corresponding value (population) is greater than 7.0 Crore. Pop() the element (Last
state_name appended in the stack named L1) Display the all the content of the stack L1
Exit() : to exit from the program

• Solution Code:

Python

D1 = {

'Maharashtra': 12.4,

'Karnataka': 6.7,

'Bihar': 10.4,

'Gujarat': 6.0,

'Andhra Pradesh': 8.4


}

L1 = []

# Push implementation

for state, population in [Link]():

if population > 7.0:

[Link](state)

print("Keys with population > 7.0 Crore pushed to stack L1.")

# Display L1 before Pop

print("\n--- Stack L1 Content (Initial) ---")

for state in reversed(L1):

print(state)

print("-" * 40)

# Pop implementation

if L1:

state_name = [Link]()

print(f"Popped element: {state_name}")

# Display L1 after Pop

print("\n--- Stack L1 Content (After Pop) ---")

for state in reversed(L1):

print(state)

print("-" * 40)

Output:

Keys with population > 7.0 Crore pushed to stack L1.

--- Stack L1 Content (Initial) ---

Andhra Pradesh
Bihar

Maharashtra

----------------------------------------

Popped element: Andhra Pradesh

--- Stack L1 Content (After Pop) ---

Bihar

Maharashtra

----------------------------------------

56. SQL Commands on WORKER and DESIG Tables

• Question: Write the SQL commands for (i) to (v) on the basis of tables following tables
(Create Tables using proper keys and insert the rows as specified) WORKER and DESIG

• Solution Code:

SQL

-- Setup

CREATE TABLE WORKER (W_ID INT PRIMARY KEY, FIRSTNAME VARCHAR(50), LASTNAME
VARCHAR(50), ADDRESS VARCHAR(100), CITY VARCHAR(50));

INSERT INTO WORKER VALUES (102, 'Sam', 'Tones', '33 Elm St.', 'Paris');

INSERT INTO WORKER VALUES (105, 'Sarah', 'Ackerman', '440 U.S', 'New York');

INSERT INTO WORKER VALUES (144, 'Manila', 'Sen', 'Friends colony', 'New York');

INSERT INTO WORKER VALUES (210, 'George', 'Smith', 'First Street', 'Howard');

CREATE TABLE DESIG (W_ID INT PRIMARY KEY, SALARY INT, BENEFITS INT, DESIGNATION
VARCHAR(50), FOREIGN KEY (W_ID) REFERENCES WORKER(W_ID));

INSERT INTO DESIG VALUES (102, 75000, 15000, 'MANAGER');

INSERT INTO DESIG VALUES (105, 85000, 25000, 'DIRECTOR');

INSERT INTO DESIG VALUES (144, 70000, 15000, 'CLERK');

INSERT INTO DESIG VALUES (210, 50000, 12000, 'CLERK');

-- (i) Display information of employees living in NewYork

SELECT *
FROM WORKER

WHERE CITY = 'New York';

-- (ii) Maximum total salary (Salary + Benefits) of Clerks

SELECT MAX(SALARY + BENEFITS) AS MaxTotalSalaryOfClerks

FROM DESIG

WHERE DESIGNATION = 'CLERK';

-- (iii) List of Designations

SELECT DISTINCT DESIGNATION

FROM DESIG;

-- (iv) Decrease the benefits by 1000

UPDATE DESIG

SET BENEFITS = BENEFITS - 1000;

-- (v) Designation and total salary of each Designation

SELECT

DESIGNATION,

SUM(SALARY + BENEFITS) AS TotalSalary

FROM DESIG

GROUP BY DESIGNATION;

Output:

-- (i)

W-ID | FIRSTNAME | LASTNAME | ADDRESS | CITY

105 | Sarah | Ackerman | 440 U.S | New York

144 | Manila | Sen | Friends colony | New York

-- (ii)

MaxTotalSalaryOfClerks

85000
-- (iii)

DESIGNATION

MANAGER

DIRECTOR

CLERK

-- (v) (Calculated BEFORE UPDATE in (iv))

DESIGNATION | TotalSalary

MANAGER | 90000

DIRECTOR | 110000

CLERK | 147000

57. SQL Commands on BOOKS and ISSUES Tables

• Question: Write the SQL commands for (i) to (v) on the basis of tables following tables
(Create Tables using proper keys and insert the rows as specified) Table: BOOKS and
Table: ISSUES

• Solution Code:

SQL

-- Setup

CREATE TABLE BOOKS (Book_ID VARCHAR(5) PRIMARY KEY, BookName VARCHAR(100),


AuthorName VARCHAR(100), Publisher VARCHAR(50), Price INT, Qty INT);

INSERT INTO BOOKS VALUES ('L01', 'Maths', 'Raman', 'ABC', 70, 20);

INSERT INTO BOOKS VALUES ('L02', 'Science', 'Agarkar', 'DEF', 90, 15);

INSERT INTO BOOKS VALUES ('L03', 'Social', 'Suresh', 'XYZ', 85, 30);

INSERT INTO BOOKS VALUES ('L04', 'Computer', 'Sumita', 'ABC', 75, 7);

INSERT INTO BOOKS VALUES ('L05', 'Telugu', 'Nannayya', 'DEF', 60, 25);

CREATE TABLE ISSUES (Book_ID VARCHAR(5) PRIMARY KEY, Qty_Issued INT, FOREIGN KEY
(Book_ID) REFERENCES BOOKS(Book_ID));

INSERT INTO ISSUES VALUES ('L02', 13);

INSERT INTO ISSUES VALUES ('L04', 5);


INSERT INTO ISSUES VALUES ('L05', 21);

-- (i) Show Book name, Author name and Price of books of ABC publisher.

SELECT BookName, AuthorName, Price

FROM BOOKS

WHERE Publisher = 'ABC';

-- (ii) Display the details of the books in descending order of their price.

SELECT *

FROM BOOKS

ORDER BY Price DESC;

-- (iii) Display the Book Id, Book name, Publisher, Price, Qty, Qty_Issued with matching Book ID.

SELECT B.Book_ID, [Link], [Link], [Link], [Link], I.Qty_Issued

FROM BOOKS B

INNER JOIN ISSUES I ON B.Book_ID = I.Book_ID;

-- (iv) Display minimum price of each publisher with their name.

SELECT Publisher, MIN(Price) AS MinPrice

FROM BOOKS

GROUP BY Publisher;

-- (v) Display the price of only those books where Qty_issued is 5.

SELECT [Link]

FROM BOOKS B

INNER JOIN ISSUES I ON B.Book_ID = I.Book_ID

WHERE I.Qty_Issued = 5;

Output:

-- (i)

BookName | AuthorName | Price

Maths | Raman | 70
Computer | Sumita | 75

-- (ii)

Book_ID | BookName | AuthorName | Publisher | Price | Qty

L02 | Science | Agarkar | DEF | 90 | 15

L03 | Social | Suresh | XYZ | 85 | 30

L04 | Computer | Sumita | ABC | 75 | 7

L01 | Maths | Raman | ABC | 70 | 20

L05 | Telugu | Nannayya | DEF | 60 | 25

-- (iii)

Book_ID | BookName | Publisher | Price | Qty | Qty_Issued

L02 | Science | DEF | 90 | 15 | 13

L04 | Computer | ABC | 75 | 7 | 5

L05 | Telugu | DEF | 60 | 25 | 21

-- (iv)

Publisher | MinPrice

ABC | 70

DEF | 60

XYZ | 85

-- (v)

Price

75

58. SQL Commands on FURNITURE and ARRIVAL Tables

• Question: Write the SQL commands for (i) to (v) on the basis of tables following tables
(Create Tables using proper keys and insert the rows as specified) Table: FURNITURE
and Table: ARRIVAL

• Solution Code:

SQL
-- Setup

CREATE TABLE FURNITURE (NO INT PRIMARY KEY, ITEM_NAME VARCHAR(100), TYPE
VARCHAR(50), PRICE INT, Discount INT);

INSERT INTO FURNITURE VALUES (1, 'White lotus', 'Double Bed', 30000, 25);

INSERT INTO FURNITURE VALUES (2, 'Pink feather', 'Baby cot', 7000, 30);

INSERT INTO FURNITURE VALUES (3, 'Dolphin', 'Office Table', 9500, 35);

INSERT INTO FURNITURE VALUES (4, 'Decent', 'Double Bed', 25000, 15);

INSERT INTO FURNITURE VALUES (5, 'Comfort', 'Sofa', 3500, 25);

CREATE TABLE ARRIVAL (NO INT PRIMARY KEY, ITEM_NAME VARCHAR(100), TYPE
VARCHAR(50), PRICE INT, DISCOUNT INT);

INSERT INTO ARRIVAL VALUES (11, 'Wood comfort', 'Double Bed', 25000, 25);

INSERT INTO ARRIVAL VALUES (12, 'Old Fox', 'Sofa', 17000, 20);

INSERT INTO ARRIVAL VALUES (13, 'Micky', 'Baby Cot', 7500, 15);

-- (i) Show all information about the Baby cots from the FURNITURE table.

SELECT *

FROM FURNITURE

WHERE TYPE = 'Baby cot';

-- (ii) Display the details of the furniture by ITEM NAME in ascending order.

SELECT *

FROM FURNITURE

ORDER BY ITEM_NAME ASC;

-- (iii) Display total price of “Double Bed”

SELECT SUM(PRICE) AS TotalDoubleBedPrice

FROM FURNITURE

WHERE TYPE = 'Double Bed';

-- (iv) Display minimum discount of arrival items.

SELECT MIN(DISCOUNT) AS MinArrivalDiscount


FROM ARRIVAL;

-- (v) Decrease the price of arrival item by 2000.

UPDATE ARRIVAL

SET PRICE = PRICE - 2000;

Output:

-- (i)

NO | ITEM NAME | TYPE | PRICE | Discount

2 | Pink feather | Baby cot | 7000 | 30

-- (ii)

NO | ITEM NAME | TYPE | PRICE | Discount

5 | Comfort | Sofa | 3500 | 25

4 | Decent | Double Bed | 25000 | 15

3 | Dolphin | Office Table | 9500 | 35

2 | Pink feather | Baby cot | 7000 | 30

1 | White lotus | Double Bed | 30000 | 25

-- (iii)

TotalDoubleBedPrice

55000

-- (iv)

MinArrivalDiscount

15

59. SQL Commands on GAMES and PLAYER Tables

• Question: Consider the following tables GAMES and PLAYER. Write SQL commands for
the statements (i) to (v) (Create Tables using proper keys and insert the rows as
specified) GAMES and PLAYER

• Solution Code:

SQL
-- Setup

CREATE TABLE GAMES (GCode INT PRIMARY KEY, GameName VARCHAR(100), Num INT,
PrizeMoney INT);

INSERT INTO GAMES VALUES (101, 'CaromBoard', 2, 5000);

INSERT INTO GAMES VALUES (102, 'Badminton', 2, 12000);

INSERT INTO GAMES VALUES (103, 'TableTennis', 4, 8000);

INSERT INTO GAMES VALUES (104, 'Chess', 2, 9000);

INSERT INTO GAMES VALUES (105, 'LawnTennis', 4, 25000);

CREATE TABLE PLAYER (PCode INT PRIMARY KEY, Name VARCHAR(100), GCode INT, FOREIGN
KEY (GCode) REFERENCES GAMES(GCode));

INSERT INTO PLAYER VALUES (1, 'Arjun', 101);

INSERT INTO PLAYER VALUES (2, 'Ravi', 105);

INSERT INTO PLAYER VALUES (3, 'Jignesh', 101);

INSERT INTO PLAYER VALUES (4, 'Nihir', 103);

INSERT INTO PLAYER VALUES (5, 'Sohil', 104);

-- (i) Display the name of players who plays CaromBoard.

SELECT [Link]

FROM PLAYER T1

INNER JOIN GAMES T2 ON [Link] = [Link]

WHERE [Link] = 'CaromBoard';

-- (ii) Display details of those game which are having PrizeMoney more than 8000.

SELECT *

FROM GAMES

WHERE PrizeMoney > 8000;

-- (iii) Display Total No. of Grames;

SELECT COUNT(*) AS TotalGames

FROM GAMES;
-- (iv) Increase the PrizeMoney by 1000 who is having Prize Money Less than 8000.

UPDATE GAMES

SET PrizeMoney = PrizeMoney + 1000

WHERE PrizeMoney < 8000;

-- (v) Arrange the records of PLAYER table in descending order by GCode.

SELECT *

FROM PLAYER

ORDER BY GCode DESC;

Output:

-- (i)

Name

Arjun

Jignesh

-- (ii)

GCode | GameName | Num | PrizeMoney

102 | Badminton | 2 | 12000

104 | Chess | 2 | 9000

105 | LawnTennis | 4 | 25000

-- (iii)

TotalGames

-- (v)

PCode | Name | GCode

2 | Ravi | 105

5 | Sohil | 104

4 | Nihir | 103

3 | Jignesh | 101
1 | Arjun | 101

60. SQL Commands on TEACHER and QUALIFICATION Tables

• Question: Consider the following tables TEACHER and QUALIFICATION. Write SQL
commands for the statements (i) to (v) (Create Tables using proper keys and insert the
rows as specified) TEACHER and QUALIFICATION

• Solution Code:

SQL

-- Setup

CREATE TABLE TEACHERS (TCode INT PRIMARY KEY, TeacherName VARCHAR(100), Subject
VARCHAR(50), Salary INT);

INSERT INTO TEACHERS VALUES (101, 'Priya', 'Hindi', 5000);

INSERT INTO TEACHERS VALUES (102, 'Sonia', 'English', 12000);

INSERT INTO TEACHERS VALUES (103, 'Anupama', 'Computer', 8000);

INSERT INTO TEACHERS VALUES (104, 'Pinki', 'English', 9000);

INSERT INTO TEACHERS VALUES (105, 'Isha', 'computer', 25000);

CREATE TABLE QUALIFICATION (QCode INT PRIMARY KEY, Qualification VARCHAR(50), TCode
INT, FOREIGN KEY (TCode) REFERENCES TEACHERS(TCode));

INSERT INTO QUALIFICATION VALUES (1, 'MA', 101);

INSERT INTO QUALIFICATION VALUES (2, 'BBA', 105);

INSERT INTO QUALIFICATION VALUES (3, 'MCA', 101);

INSERT INTO QUALIFICATION VALUES (4, '[Link]', 103);

INSERT INTO QUALIFICATION VALUES (5, 'MA', 104);

-- (i) Display the name of Teacher whose qualification is ‘MA’

SELECT [Link]

FROM TEACHERS T1

INNER JOIN QUALIFICATION T2 ON [Link] = [Link]

WHERE [Link] = 'MA';

-- (ii) Display details of those teachers which are having Salary more than 8000.
SELECT *

FROM TEACHERS

WHERE Salary > 8000;

-- (iii) Display Total No. of teachers;

SELECT COUNT(*) AS TotalTeachers

FROM TEACHERS;

-- (iv) Decrease the Salary by 1000 who is having salary Less than 8000.

UPDATE TEACHERS

SET Salary = Salary - 1000

WHERE Salary < 8000;

-- (v) Display the total no. of teacher in each subject with their subject.

SELECT

Subject, COUNT(TCode) AS TotalTeachers

FROM TEACHERS

GROUP BY Subject;

Output:

-- (i)

TeacherName

Priya

Pinki

-- (ii)

TCode | TeacherName | Subject | Salary

102 | Sonia | English | 12000

104 | Pinki | English | 9000

105 | Isha | computer | 25000

-- (iii)
TotalTeachers

-- (v)

Subject | TotalTeachers

Hindi | 1

English | 2

Computer | 1

computer | 1

You might also like