This page contains the NCERT Computer Science class 11 chapter 10 Tuples and Dictionaries. You can find the solutions for the chapter 10 of NCERT class 11 Computer Science Exercise. So is the case if you are looking for NCERT class 11 Computer Science related topic Tuples and Dictionaries questions and answers for the Exercise
Exercise
1. Consider the following tuples, tuple1 and tuple2:
tuple1 = (23,1,45,67,45,9,55,45)tuple2 = (100,200)Find the output of the following statements:
i.
print(tuple1.index(45))ii.
print(tuple1.count(45))iii.
print(tuple1 + tuple2)iv.
print(len(tuple2))v.
print(max(tuple1))vi.
print(min(tuple1))vii.
print(sum(tuple2))viii.
print(sorted(tuple1))print(tuple1)i.
tuple1 = (23,1,45,67,45,9,55,45)
print(tuple1.index(45))
Output:
2
Explanation: index() returns the first position of 45 (0-based indexing).
ii.
tuple1 = (23,1,45,67,45,9,55,45)
print(tuple1.count(45))
Output:
3
Explanation: count() returns how many times 45 appears.
iii.
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
print(tuple1 + tuple2)
Output:
(23, 1, 45, 67, 45, 9, 55, 45, 100, 200)
Explanation: The + operator concatenates two tuples.
iv.
tuple2 = (100,200)
print(len(tuple2))
Output:
2
Explanation: len() gives the number of elements in the tuple.
v.
tuple1 = (23,1,45,67,45,9,55,45)
print(max(tuple1))
Output:
67
Explanation: max() returns the largest value in the tuple.
vi.
tuple1 = (23,1,45,67,45,9,55,45)
print(min(tuple1))
Output:
1
Explanation: min() returns the smallest value in the tuple.
vii.
tuple2 = (100,200)
print(sum(tuple2))
Output:
300
Explanation: sum() adds all numeric elements in the tuple.
viii.
tuple1 = (23,1,45,67,45,9,55,45)
print(sorted(tuple1))
print(tuple1)
Output:
[1, 9, 23, 45, 45, 45, 55, 67]
(23, 1, 45, 67, 45, 9, 55, 45)
Explanation: sorted() returns a new sorted list; the original tuple stays unchanged.
2. Consider the following dictionary stateCapital:
stateCapital = {"AndhraPradesh":"Hyderabad", "Bihar":"Patna","Maharashtra":"Mumbai", "Rajasthan":"Jaipur"}Find the output of the following statements:
i.print(stateCapital.get("Bihar"))ii.print(stateCapital.keys())iii.print(stateCapital.values())iv.print(stateCapital.items())v.print(len(stateCapital))vi.print("Maharashtra" in stateCapital)vii.print(stateCapital.get("Assam"))viii.del stateCapital["Rajasthan"]ix.print(stateCapital)i.
stateCapital = {
"AndhraPradesh": "Hyderabad",
"Bihar": "Patna",
"Maharashtra": "Mumbai",
"Rajasthan": "Jaipur"
}
print(stateCapital.get("Bihar"))
Sample Output:
Patna
Explanation:
get() returns the value for the key “Bihar”.
ii.
stateCapital = {
"AndhraPradesh": "Hyderabad",
"Bihar": "Patna",
"Maharashtra": "Mumbai",
"Rajasthan": "Jaipur"
}
print(stateCapital.keys())
Sample Output:
dict_keys(['AndhraPradesh', 'Bihar', 'Maharashtra', 'Rajasthan'])
Explanation:
keys() returns a view of all keys in the dictionary.
iii.
stateCapital = {
"AndhraPradesh": "Hyderabad",
"Bihar": "Patna",
"Maharashtra": "Mumbai",
"Rajasthan": "Jaipur"
}
print(stateCapital.values())
Sample Output:
dict_values(['Hyderabad', 'Patna', 'Mumbai', 'Jaipur'])
Explanation:
values() returns a view of all values in the dictionary.
iv.
stateCapital = {
"AndhraPradesh": "Hyderabad",
"Bihar": "Patna",
"Maharashtra": "Mumbai",
"Rajasthan": "Jaipur"
}
print(stateCapital.items())
Sample Output:
dict_items([('AndhraPradesh', 'Hyderabad'), ('Bihar', 'Patna'), ('Maharashtra', 'Mumbai'), ('Rajasthan', 'Jaipur')])
Explanation:
items() returns key-value pairs as tuples.
v.
stateCapital = {
"AndhraPradesh": "Hyderabad",
"Bihar": "Patna",
"Maharashtra": "Mumbai",
"Rajasthan": "Jaipur"
}
print(len(stateCapital))
Sample Output:
4
Explanation:
len() returns the number of key-value pairs.
vi.
stateCapital = {
"AndhraPradesh": "Hyderabad",
"Bihar": "Patna",
"Maharashtra": "Mumbai",
"Rajasthan": "Jaipur"
}
print("Maharashtra" in stateCapital)
Sample Output:
True
Explanation:
The in operator checks if a key exists in the dictionary.
vii.
stateCapital = {
"AndhraPradesh": "Hyderabad",
"Bihar": "Patna",
"Maharashtra": "Mumbai",
"Rajasthan": "Jaipur"
}
print(stateCapital.get("Assam"))
Sample Output:
None
Explanation:
get() returns None when the key is missing.
viii.
stateCapital = {
"AndhraPradesh": "Hyderabad",
"Bihar": "Patna",
"Maharashtra": "Mumbai",
"Rajasthan": "Jaipur"
}
del stateCapital["Rajasthan"]
Sample Output:
No output (key removed)
Explanation:
The del statement removes the “Rajasthan” entry.
ix.
stateCapital = {
"AndhraPradesh": "Hyderabad",
"Bihar": "Patna",
"Maharashtra": "Mumbai",
"Rajasthan": "Jaipur"
}
del stateCapital["Rajasthan"]
print(stateCapital)
Sample Output:
{'AndhraPradesh': 'Hyderabad', 'Bihar': 'Patna', 'Maharashtra': 'Mumbai'}
Explanation:
The printed dictionary no longer includes the deleted key.
3. “Lists and Tuples are ordered”. Explain.
In Python, lists and tuples are called ordered because their elements are stored in the same sequence in which we insert them.
So, each element has a fixed position called its index (starting from 0):
•
The element at index 0 will always remain the first element.
•
The element at index 1 will always remain the second element, and so on.
•
We can access elements using indexing like list[0], tuple[1], etc.
Example:
# List example
L = ["Pen", "Pencil", "Eraser"]
print(L[0]) # Pen
print(L[2]) # Eraser
# Tuple example
T = (10, 20, 30, 40)
print(T[1]) # 20
print(T[3]) # 40
Here, the order is maintained exactly as entered, so the same item is found at the same index every time—therefore lists and tuples are ordered collections.
4. With the help of an example show how can you return more than one value from a function.
In Python, a function can return more than one value by returning values separated by commas. Python packs these returned values into a tuple. At the time of calling the function, we can unpack the tuple into separate variables.
Example:
def operations(a, b):
"""
This function returns more than one value:
1) sum of a and b
2) difference of a and b
3) product of a and b
The returned values are packed into a tuple.
"""
s = a + b
d = a - b
p = a * b
return s, d, p # returns multiple values (as a tuple)
# Calling the function and unpacking the returned tuple
sum_val, diff_val, prod_val = operations(12, 4)
print("Sum =", sum_val)
print("Difference =", diff_val)
print("Product =", prod_val)
Sample Output:
Sum = 16
Difference = 8
Product = 48
5. What advantages do tuples have over lists?
Tuples have these advantages over lists:
1.
Tuples are immutable (cannot be changed). Once a tuple is created, we cannot add, remove, or change its elements. That’s why, when we sort a tuple using sorted(), the original tuple stays unchanged.
2.
They are good for fixed data (data that should not change). Since tuples are immutable, they are safer to store “final” information like records/details. In this chapter’s case study hint, the dictionary value is suggested as an immutable data type (so it won’t change accidentally).
3.
Useful in dictionaries where an immutable value is needed. In the SMIS solution style shown, marks are converted into a tuple to make them immutable before storing.
6. When to use tuple or dictionary in Python. Give some examples of programming situations mentioning their usefulness.
When to use a
tupleA tuple should be used when we need a fixed (unchangeable) collection of values (i.e., the data should not change).
Usefulness + examples:
•
To store related values as one record (fixed data), like a student’s basic details: `student = (“Ananya”, “X”, “A”)`
•
To store marks of a student (once entered, you don’t want accidental changes):
marks = (78, 85, 91, 88)•
To return multiple values from a function (Python returns them as a tuple):
`return sum_val, avg_val`When to use a
dictionaryUse a dictionary when you want to store data as key : value pairs, and you need fast searching using a unique key.
Usefulness + examples:
•
Student record system (SMIS type):
Key = Roll Number, Value = (Name, Percentage)
•
Phone book:
Key = Name, Value = Phone number
•
Menu / Price list:
Key = Item name, Value = Price
Example (tuple + dictionary together)
(Shows a very common and useful situation: dictionary for searching + tuple for fixed record)
# Dictionary: roll number is the key (easy to search)
# Tuple: (name, percentage) is fixed record (immutable)
students = {
1: ("Ananya", 92.5),
2: ("Ravi", 88.0),
3: ("Meera", 95.0)
}
roll = int(input("Enter roll number: "))
if roll in students:
name, percent = students[roll] # tuple unpacking
print("Name:", name)
print("Percentage:", percent)
else:
print("Roll number not found.")
So, in short:
•
Use tuple for fixed data (immutable record).
•
Use dictionary when you need mapping + quick search using a key.
7. Prove with the help of an example that the variable is rebuilt in case of immutable data types.
In Python, some data types are immutable (cannot be changed), e.g. int, float, str, tuple. So, if we “change” their value, Python actually creates a new object and the variable name starts pointing to this new object (i.e., the variable is rebuilt / re-assigned).
How it works:
When we “change” an integer, for example:
1.
Python creates the new value in a different memory location.
2.
The variable name is updated to point to that new memory address.
3.
The old value remains in memory until it is cleaned up by Python’s Garbage Collector (if no other variables are pointing to it).
Example 1: Integer (immutable)
# Proving rebuild using id() for an immutable type (int)
x = 10
print("Before change:")
print("x =", x, " id =", id(x))
# This does NOT change the same integer object.
# A NEW integer object is created and x now refers to it.
x = x + 5
print("\nAfter change:")
print("x =", x, " id =", id(x))
Sample Output (ids will differ on your computer)
Before change:
x = 10 id = 140734879813232
After change:
x = 15 id = 140734879813392
✅ Observation: The id changes, so `x` is now pointing to a new object → the variable got rebuilt.
Example 2: Tuple (immutable)
# Tuple is immutable, so we cannot change it directly.
t = (1, 2, 3)
print("Before change:")
print("t =", t, " id =", id(t))
# "Modify" by creating a NEW tuple (rebuilding)
t = t + (4,)
print("\nAfter change:")
print("t =", t, " id =", id(t))
Sample Output (ids will differ)
Before change:
t = (1, 2, 3) id = 140516823471872
After change:
t = (1, 2, 3, 4) id = 140516823476160
✅ Observation: Tuple can’t be changed in-place, so Python creates a new tuple, and `t` refers to it (tuple is rebuilt). This matches the chapter idea that when we modify, we rebuild the tuple because it is immutable.
8.
TypeError occurs while statement 2 is running.Give reason. How can it be corrected?
>>> tuple1 = (5) #statement 1
>>> len(tuple1) #statement 2
>>> tuple1 = (5) # Statement 1
len(tuple1) # Statement 2
Reason (Why TypeError happens):
•
In statement 1, tuple1 = (5) does NOT create a tuple.
•
(5) is just an integer inside brackets, so tuple1 becomes an int.
•
But len() works only on sequences/collections like string, list, tuple, dictionary, etc.
•
So len(tuple1) gives TypeError because an int has no length.
Correction (How to fix it)
To create a single-element tuple, we must put a comma after the element:
>>> tuple1 = (5,) # corrected statement 1
>>> print(len(tuple1)) # statement 2
Why comma works?
Because in Python, values separated by commas are packed as a tuple (this is the same idea used when returning multiple values).
Sample Output
>>> tuple1 = (5,)
>>> len(tuple1)
1
(Optionally, we can verify the type too:)
>>> type(tuple1)
<class 'tuple'>
Programming Problems
1. Write a program to read email IDs of n number of students and store them in a tuple. Create two new tuples, one to store only the usernames from the email IDs and second to store domain names from the email IDs. Print all three tuples at the end of the program. [Hint: You may use the function split()]
✅ Python Program
# Read number of students
n = int(input("Enter number of students: "))
emails = []
# Input all email IDs
for i in range(n):
email = input("Enter email " + str(i + 1) + ": ")
emails.append(email)
# Convert list to tuple
email_tuple = tuple(emails)
# Split emails into username and domain
usernames = []
domains = []
for email in email_tuple:
parts = email.split("@")
usernames.append(parts[0])
domains.append(parts[1])
# Final tuples
username_tuple = tuple(usernames)
domain_tuple = tuple(domains)
# Display results
print("\nAll Emails:", email_tuple)
print("Usernames:", username_tuple)
print("Domains:", domain_tuple)
Sample Output
Enter number of students: 3
Enter email 1: riya@gmail.com
Enter email 2: aman@school.edu
Enter email 3: sara@yahoo.com
All Emails: ('riya@gmail.com', 'aman@school.edu', 'sara@yahoo.com')
Usernames: ('riya', 'aman', 'sara')
Domains: ('gmail.com', 'school.edu', 'yahoo.com')
2. Write a program to input names of n students and store them in a tuple. Also, input a name from the user and find if this student is present in the tuple or not.
We can accomplish these by:
(a)
writing a user defined function
(b)
using the built-in function
Part (a) — ✅ Python Program (User Defined Function)
# User-defined function to check presence
def is_present(name, name_tuple):
for item in name_tuple:
if item == name:
return True
return False
# Read names
n = int(input("Enter number of students: "))
names = []
for i in range(n):
student = input("Enter name " + str(i + 1) + ": ")
names.append(student)
# Convert to tuple and search
name_tuple = tuple(names)
search_name = input("Enter name to search: ")
# Display result
if is_present(search_name, name_tuple):
print("Student found.")
else:
print("Student not found.")
Sample Output
Enter number of students: 4
Enter name 1: Riya
Enter name 2: Aman
Enter name 3: Sara
Enter name 4: Neel
Enter name to search: Sara
Student found.
Part (b) — ✅ Python Program (Built-in Function)
# Read names
n = int(input("Enter number of students: "))
names = []
for i in range(n):
student = input("Enter name " + str(i + 1) + ": ")
names.append(student)
# Convert to tuple and search
name_tuple = tuple(names)
search_name = input("Enter name to search: ")
# Use built-in membership operator
if search_name in name_tuple:
print("Student found.")
else:
print("Student not found.")
Sample Output
Enter number of students: 3
Enter name 1: Asha
Enter name 2: Dev
Enter name 3: Kabir
Enter name to search: Rohan
Student not found.
3. Write a Python program to find the highest 2 values in a dictionary.
✅ Python Program
# Dictionary of sample values
data = {
"A": 15,
"B": 8,
"C": 22,
"D": 19,
"E": 12
}
# Get and sort values in descending order
values = list(data.values())
values.sort(reverse=True)
# Pick the top two values
highest_two = (values[0], values[1])
print("Highest two values:", highest_two)
Sample Output
Highest two values: (22, 19)
4. Write a Python program to create a dictionary from a string.
Note: Track the count of the letters from the string.
Sample string : ‘w3resource’
Expected output : {‘3’: 1, ‘s’: 1, ‘r’: 2, ‘u’: 1, ‘w’: 1, ‘c’: 1, ‘e’: 2, ‘o’: 1}
✅ Python Program
# Read input string
text = input("Enter a string: ")
count_dict = {}
# Count each character
for ch in text:
if ch in count_dict:
count_dict[ch] += 1
else:
count_dict[ch] = 1
# Display dictionary
print(count_dict)
Sample Output
Enter a string: w3resource
{'w': 1, '3': 1, 'r': 2, 'e': 2, 's': 1, 'o': 1, 'u': 1, 'c': 1}
Sample Output
Enter a string: hello
{'h': 1, 'e': 1, 'l': 2, 'o': 1}
5. Write a program to input your friends’ names and their Phone Numbers and store them in the dictionary as the key-value pair. Perform the following operations on the dictionary:
a)
Display the name and phone number of all your friends
b)
Add a new key-value pair in this dictionary and display the modified dictionary
c)
Delete a particular friend from the dictionary
d)
Modify the phone number of an existing friend
e)
Check if a friend is present in the dictionary or not
f)
Display the dictionary in sorted order of names
✅ Python Program
# Input number of friends
n = int(input("Enter number of friends: "))
friends = {}
# Read names and phone numbers
for i in range(n):
name = input("Enter name " + str(i + 1) + ": ")
phone = input("Enter phone for " + name + ": ")
friends[name] = phone
# (a) Display all friends
print("\nAll friends:")
for name, phone in friends.items():
print(name, "-", phone)
# (b) Add a new friend
new_name = input("\nEnter new friend name: ")
new_phone = input("Enter phone for " + new_name + ": ")
friends[new_name] = new_phone
print("After adding:", friends)
# (c) Delete a friend
del_name = input("\nEnter name to delete: ")
if del_name in friends:
del friends[del_name]
print("After deletion:", friends)
else:
print("Friend not found.")
# (d) Modify phone number
mod_name = input("\nEnter name to modify: ")
if mod_name in friends:
mod_phone = input("Enter new phone for " + mod_name + ": ")
friends[mod_name] = mod_phone
print("After modification:", friends)
else:
print("Friend not found.")
# (e) Check if friend is present
check_name = input("\nEnter name to check: ")
if check_name in friends:
print(check_name, "is present.")
else:
print(check_name, "is not present.")
# (f) Display dictionary in sorted order
print("\nSorted by name:")
for name in sorted(friends.keys()):
print(name, "-", friends[name])
Sample Output
Enter number of friends: 2
Enter name 1: Asha
Enter phone for Asha: 9999999991
Enter name 2: Dev
Enter phone for Dev: 9999999992
All friends:
Asha - 9999999991
Dev - 9999999992
Enter new friend name: Riya
Enter phone for Riya: 9999999993
After adding: {'Asha': '9999999991', 'Dev': '9999999992', 'Riya': '9999999993'}
Enter name to delete: Dev
After deletion: {'Asha': '9999999991', 'Riya': '9999999993'}
Enter name to modify: Asha
Enter new phone for Asha: 9999999994
After modification: {'Asha': '9999999994', 'Riya': '9999999993'}
Enter name to check: Riya
Riya is present.
Sorted by name:
Asha - 9999999994
Riya - 9999999993
Case Study Based Question
For the SMIS System given in Chapter 5, let us do the following: Write a program to take in the roll number, name and percentage of marks for n students of Class X. Write user defined functions to
•
accept details of the n students (n is the number of students)
•
search details of a particular student on the basis of roll number and display result
•
display the result of all the students
•
find the topper amongst them
•
find the subject toppers amongst them
(Hint: use Dictionary, where the key can be roll number and the value is an immutable data type containing name and percentage)
Let’s peer review the case studies of others based on the parameters given under “DOCUMENTATION TIPS” at the end of Chapter 5 and provide a feedback to them.
# ✅ Python Program (well-commented)
# SMIS (Student Management Information System) - Case Study
# Chapter: Tuples and Dictionaries
# Class XI level program using:
# - Dictionary for storing student data
# - Tuple (immutable) as dictionary value
# ---------------------------------------------------------
# Data structure used:
# students = {
# roll_no: (name, marks_tuple, percentage)
# }
# where:
# - roll_no is the KEY (unique)
# - value is a TUPLE (immutable):
# name -> string
# marks_tuple -> tuple of marks for subjects (immutable)
# percentage -> float
# ---------------------------------------------------------
def accept_details(n, subjects):
"""
Accepts details of n students and returns a dictionary.
Parameters:
n (int): Number of students
subjects (tuple): Fixed list of subject names
Returns:
dict: students dictionary
key -> roll number (int)
value -> (name, marks_tuple, percentage) [immutable tuple]
"""
students = {}
for i in range(1, n + 1):
print("\n--- Enter details for Student " + str(i) + " ---")
roll = int(input("Roll Number: "))
name = input("Name: ").strip()
# Take marks for each subject
marks_list = []
for sub in subjects:
mark = float(input("Marks in " + sub + " (out of 100): "))
marks_list.append(mark)
# Convert marks to tuple to make it immutable
marks_tuple = tuple(marks_list)
# Calculate percentage
total = sum(marks_tuple)
percentage = (total / (len(subjects) * 100)) * 100
# Store in dictionary (value is immutable tuple)
students[roll] = (name, marks_tuple, percentage)
return students
def search_student(students, roll):
"""
Searches for a student by roll number and prints their result.
Parameters:
students (dict): student dictionary
roll (int): roll number to search
"""
if roll in students:
name, marks_tuple, percentage = students[roll]
print("\n✅ Student Found!")
print("Roll No :", roll)
print("Name :", name)
print("Marks :", marks_tuple)
print("Percentage :", format(percentage, ".2f") + "%")
else:
print("\n❌ No student found with Roll No:", roll)
def display_all_results(students, subjects):
"""
Displays results of all students in a neat format (sorted by roll number).
Parameters:
students (dict): student dictionary
subjects (tuple): list of subjects
"""
if not students:
print("\nNo data to display.")
return
print("\n========== ALL STUDENTS RESULT ==========")
print("Subjects:", ", ".join(subjects))
print("----------------------------------------")
print("Roll\tName\t\tPercentage")
print("----------------------------------------")
for roll in sorted(students.keys()):
name, marks_tuple, percentage = students[roll]
print(format(roll) + "\t" + format(name, "<12") + "\t" + format(percentage, ".2f") + "%")
print("----------------------------------------")
def find_topper(students):
"""
Finds topper(s) based on highest percentage.
If more than one student has same highest percentage, all are toppers.
Parameters:
students (dict): student dictionary
"""
if not students:
print("\nNo data available.")
return
# Find maximum percentage
max_percent = max(students[roll][2] for roll in students)
print("\n========== TOPPER(S) ==========")
print("Highest Percentage:", format(max_percent, ".2f") + "%")
for roll in sorted(students.keys()):
name, marks_tuple, percentage = students[roll]
if percentage == max_percent:
print("Roll: " + format(roll) + ", Name: " + name + ", Percentage: " + format(percentage, ".2f") + "%")
def find_subject_toppers(students, subjects):
"""
Finds subject toppers for each subject (highest marks in that subject).
Handles ties (more than one topper possible).
Parameters:
students (dict): student dictionary
subjects (tuple): list of subjects
"""
if not students:
print("\nNo data available.")
return
print("\n========== SUBJECT TOPPERS ==========")
for idx, sub in enumerate(subjects):
# Highest marks for this subject
highest_marks = max(students[roll][1][idx] for roll in students)
print("\nSubject: " + sub)
print("Highest Marks:", highest_marks)
# Print all students who got highest marks (tie possible)
for roll in sorted(students.keys()):
name, marks_tuple, percentage = students[roll]
if marks_tuple[idx] == highest_marks:
print(" Roll: " + format(roll) + ", Name: " + name)
# ------------------- MAIN PROGRAM -------------------
# Fixed subjects (you can change if your school has different subjects)
subjects = ("English", "Maths", "Science", "Social Science", "Computer")
n = int(input("Enter number of students (Class X): "))
# 1) Accept details
students = accept_details(n, subjects)
# 2) Display all results
display_all_results(students, subjects)
# 3) Search a student by roll number
roll_to_search = int(input("\nEnter roll number to search: "))
search_student(students, roll_to_search)
# 4) Find topper
find_topper(students)
# 5) Find subject toppers
find_subject_toppers(students, subjects)
Sample Output
Enter number of students (Class X): 2
--- Enter details for Student 1 ---
Roll Number: 101
Name: Asha
Marks in English (out of 100): 78
Marks in Maths (out of 100): 88
Marks in Science (out of 100): 91
Marks in Social Science (out of 100): 75
Marks in Computer (out of 100): 95
--- Enter details for Student 2 ---
Roll Number: 102
Name: Dev
Marks in English (out of 100): 82
Marks in Maths (out of 100): 90
Marks in Science (out of 100): 87
Marks in Social Science (out of 100): 80
Marks in Computer (out of 100): 92
========== ALL STUDENTS RESULT ==========
Subjects: English, Maths, Science, Social Science, Computer
----------------------------------------
Roll Name Percentage
----------------------------------------
101 Asha 85.40%
102 Dev 86.20%
----------------------------------------
Enter roll number to search: 101
✅ Student Found!
Roll No : 101
Name : Asha
Marks : (78.0, 88.0, 91.0, 75.0, 95.0)
Percentage : 85.40%
========== TOPPER(S) ==========
Highest Percentage: 86.20%
Roll: 102, Name: Dev, Percentage: 86.20%
========== SUBJECT TOPPERS ==========
Subject: English
Highest Marks: 82.0
Roll: 102, Name: Dev
Subject: Maths
Highest Marks: 90.0
Roll: 102, Name: Dev
Subject: Science
Highest Marks: 91.0
Roll: 101, Name: Asha
Subject: Social Science
Highest Marks: 80.0
Roll: 102, Name: Dev
Subject: Computer
Highest Marks: 95.0
Roll: 101, Name: Asha
✅ This matches the Hint (Dictionary + Immutable)
–
We use `students` as a dictionary
–
Key = `roll number`
–
Value = `(name, marks_tuple, percentage)` which is a tuple, so it is immutable.
✅ Peer Review (Documentation Tips) – Checklist + Sample Feedback
Since the question also asks:
“Let’s peer review the case studies of others based on the parameters given under DOCUMENTATION TIPS…”
Here’s a simple peer-review format you can use.
✅ Peer Review Checklist (Documentation Tips style)
Check if the program has:
1.
Title / Problem Statement (What the program does)
2.
Meaningful variable names (`students`, `roll`, `percentage` etc.)
3.
Proper comments (explains important parts)
4.
User-defined functions (properly used, not everything in main)
5.
Input prompts are clear
6.
Output is readable (headings, table, formatting)
7.
Logic is correct (search, topper, subject topper, display all)
8.
Handles ties (more than one topper possible)
9.
Uses dictionary correctly (roll number as key)
10.
Uses immutable data type as dictionary value (tuple)
✅ Sample Feedback (what you can write)
Feedback:
Your program is well-structured and uses functions properly. Variable names are meaningful and the output format is clear. You have also used dictionary correctly with roll number as key.
One improvement: add comments near the topper logic and handle the case when the same roll number is entered twice. Also include a short header comment that explains the data structure used.
Case Study-based Questions
1. A bank is a financial institution which is involved in borrowing and lending of money. With advancement in technology, online banking, also known as internet banking allows customers of a bank to conduct a range of financial transactions through the bank’s website anytime, anywhere. As part of initial investigation you are suggested to
•
collect a bank’s application form. After careful analysis of the form, identify the information required for opening a savings account. Also enquire about the rate of interest offered for a saving account.
•
The basic two operations performed on an account are Deposit and Withdrawal. Write a menu driven program that accepts either of the two choices of Deposit and Withdrawal, then accepts an amount, performs the transaction and accordingly displays the balance.
Remember, every bank has a requirement of minimum balance which needs to be taken care of during withdrawal operations. Enquire about the minimum balance required in your bank.
•
Collect the interest rates for opening a fixed deposit in various slabs in a savings bank account. Remember, rates may be different for senior citizens.
Finally, write a menu driven program having the following options (use functions and appropriate data types):
•
Open a savings bank account
•
Deposit money
•
Withdraw money
•
Take details, such as amount and period for a Fixed Deposit and display its maturity amount for a particular customer.
Part A: Information needed to open a Savings Account (typical)
From a typical bank form, we usually need:
•
Name, Father/Mother/Guardian name
•
Date of birth, gender
•
Mobile number, email
•
Address (house, street, city, state, PIN)
•
Identity proof (Aadhaar/Passport/Driving License etc.)
•
PAN (often required)
•
Occupation
•
Nominee details
•
Specimen signature
Savings interest rate and minimum balance depend on the bank, so in the program below let’s keep them as variables so that we can edit easily.
✅ Complete Python Solution (Menu-driven + functions)
"""
BANK CASE STUDY (Tuples & Dictionaries)
--------------------------------------
We use:
1) Dictionary: accounts
- key : account number (int)
- value : immutable tuple (name, phone, address, is_senior, balance)
2) Tuple for FD slabs (immutable interest-rate table)
Whenever balance changes (deposit/withdraw), we do NOT modify the tuple
(because tuple is immutable). Instead, we CREATE A NEW TUPLE and replace it.
This is exactly the tuple concept from the chapter.
"""
# ------------------ REALISTIC ASSUMPTIONS ------------------
MIN_BALANCE = 2000.0 # realistic minimum balance
SAVINGS_INTEREST_RATE = 3.0 # just an info value
# FD slabs as an IMMUTABLE tuple of tuples:
# (min_years, max_years, rate_regular, rate_senior)
FD_SLABS = (
(1.0, 2.0, 6.70, 7.20),
(2.0, 3.0, 6.90, 7.40),
(3.0, 5.0, 7.00, 7.50),
)
# Account record tuple index positions (for readability)
IDX_NAME = 0
IDX_PHONE = 1
IDX_ADDRESS = 2
IDX_SENIOR = 3
IDX_BAL = 4
# ------------------ DICTIONARY STORAGE ------------------
accounts = {} # account_no -> (name, phone, address, is_senior, balance)
next_acc_no = 1001 # starting account number
# ------------------ SMALL INPUT HELPERS ------------------
def input_float(prompt):
"""Read a non-negative float safely."""
while True:
try:
x = float(input(prompt))
if x < 0:
print("Amount cannot be negative. Try again.")
continue
return x
except ValueError:
print("Invalid number. Please enter again.")
def input_yes_no(prompt):
"""Return True for Yes, False for No."""
while True:
ans = input(prompt).strip().lower()
if ans in ("yes", "y"):
return True
if ans in ("no", "n"):
return False
print("Please type Yes or No.")
# ------------------ TUPLE "REBUILD" FUNCTION ------------------
def rebuild_account(old_tuple, new_balance):
"""
Returns a NEW tuple with the same details but updated balance.
This demonstrates immutability: we rebuild the tuple.
"""
return (
old_tuple[IDX_NAME],
old_tuple[IDX_PHONE],
old_tuple[IDX_ADDRESS],
old_tuple[IDX_SENIOR],
new_balance
)
# ------------------ MAIN FEATURES ------------------
def open_savings_account():
"""
Open a savings account and store details in dictionary as a tuple record.
"""
global next_acc_no
print("\n--- OPEN SAVINGS ACCOUNT ---")
name = input("Customer Name: ").strip()
phone = input("Mobile Number: ").strip()
address = input("Address: ").strip()
is_senior = input_yes_no("Is the customer a senior citizen? (Yes/No): ")
opening = input_float("Opening Balance (minimum " + str(MIN_BALANCE) + "): ")
if opening < MIN_BALANCE:
print("❌ Account cannot be opened. Minimum balance is " + str(MIN_BALANCE) + ".")
return
acc_no = next_acc_no
next_acc_no += 1
# Create an immutable tuple record
record = (name, phone, address, is_senior, opening)
# Store in dictionary
accounts[acc_no] = record
print("\n✅ Account created successfully!")
print("Account Number:", acc_no)
print("Current Balance:", accounts[acc_no][IDX_BAL])
def deposit_money():
"""
Deposit amount: rebuild tuple with updated balance.
"""
print("\n--- DEPOSIT MONEY ---")
acc_no = int(input("Enter Account Number: "))
if acc_no not in accounts:
print("❌ Account not found.")
return
amount = input_float("Enter deposit amount: ")
old = accounts[acc_no]
new_balance = old[IDX_BAL] + amount
# Rebuild tuple (immutable update)
accounts[acc_no] = rebuild_account(old, new_balance)
print("✅ Deposit successful.")
print("Updated Balance:", accounts[acc_no][IDX_BAL])
def withdraw_money():
"""
Withdraw amount with minimum balance rule:
balance after withdrawal must be >= MIN_BALANCE
"""
print("\n--- WITHDRAW MONEY ---")
acc_no = int(input("Enter Account Number: "))
if acc_no not in accounts:
print("❌ Account not found.")
return
amount = input_float("Enter withdrawal amount: ")
old = accounts[acc_no]
current = old[IDX_BAL]
if current - amount < MIN_BALANCE:
print("❌ Withdrawal denied!")
print("Minimum balance of " + str(MIN_BALANCE) + " must be maintained.")
print("Current Balance:", current)
return
new_balance = current - amount
accounts[acc_no] = rebuild_account(old, new_balance)
print("✅ Withdrawal successful.")
print("Updated Balance:", accounts[acc_no][IDX_BAL])
def show_account_details():
"""Display account details using tuple indexes."""
print("\n--- ACCOUNT DETAILS ---")
acc_no = int(input("Enter Account Number: "))
if acc_no not in accounts:
print("❌ Account not found.")
return
rec = accounts[acc_no]
print("\nAccount Number:", acc_no)
print("Name:", rec[IDX_NAME])
print("Phone:", rec[IDX_PHONE])
print("Address:", rec[IDX_ADDRESS])
print("Senior Citizen:", "Yes" if rec[IDX_SENIOR] else "No")
print("Balance:", rec[IDX_BAL])
# ------------------ FD FUNCTIONS (TUPLES) ------------------
def get_fd_rate(years, is_senior):
"""
Find FD rate by searching FD_SLABS (tuple of tuples).
Returns applicable rate (float) or None if no slab matches.
"""
for (min_y, max_y, rate_reg, rate_sen) in FD_SLABS:
if min_y <= years <= max_y:
return rate_sen if is_senior else rate_reg
return None
def fd_maturity_amount(principal, years, rate_percent):
"""
Compound interest (yearly compounding):
A = P * (1 + r/100) ^ t
"""
r = rate_percent / 100
return principal * ((1 + r) ** years)
def fixed_deposit_maturity():
"""FD maturity for a customer, using tuple slabs + tuple account record."""
print("\n--- FIXED DEPOSIT (FD) MATURITY ---")
acc_no = int(input("Enter Account Number: "))
if acc_no not in accounts:
print("❌ Account not found.")
return
principal = input_float("Enter FD Amount (Principal): ")
years = input_float("Enter FD Period in years (Example: 2 or 3): ")
rec = accounts[acc_no]
is_senior = rec[IDX_SENIOR]
rate = get_fd_rate(years, is_senior)
if rate is None:
print("❌ No FD slab found for this period.")
print("Please update FD_SLABS.")
return
maturity = fd_maturity_amount(principal, years, rate)
print("\n✅ FD Details")
print("Customer:", rec[IDX_NAME])
print("FD Amount:", principal)
print("Period (years):", years)
print("Rate (% p.a.):", rate)
print("Maturity Amount:", round(maturity, 2))
# ------------------ MENU ------------------
def menu():
"""Menu-driven program as asked in the case study."""
while True:
print("\n================= BANK MENU =================")
print("1. Open a Savings Bank Account")
print("2. Deposit Money")
print("3. Withdraw Money")
print("4. Fixed Deposit (FD) Maturity Amount")
print("5. Show Account Details")
print("6. Exit")
print("============================================")
choice = input("Enter your choice (1-6): ").strip()
if choice == "1":
open_savings_account()
elif choice == "2":
deposit_money()
elif choice == "3":
withdraw_money()
elif choice == "4":
fixed_deposit_maturity()
elif choice == "5":
show_account_details()
elif choice == "6":
print("Thank you! Exiting program.")
break
else:
print("Invalid choice. Please choose from 1 to 6.")
# Run the program
menu()
Sample Output
================= BANK MENU =================
1. Open a Savings Bank Account
2. Deposit Money
3. Withdraw Money
4. Fixed Deposit (FD) Maturity Amount
5. Show Account Details
6. Exit
============================================
Enter your choice (1-6): 1
--- OPEN SAVINGS ACCOUNT ---
Customer Name: Riya
Mobile Number: 9876543210
Address: Delhi
Is the customer a senior citizen? (Yes/No): No
Opening Balance (minimum 1000): 5000
✅ Account created successfully!
Account Number: 1001
Current Balance: 5000.0
================= BANK MENU =================
1. Open a Savings Bank Account
2. Deposit Money
3. Withdraw Money
4. Fixed Deposit (FD) Maturity Amount
5. Show Account Details
6. Exit
============================================
Enter your choice (1-6): 5
--- ACCOUNT DETAILS ---
Enter Account Number: 1001
Account Number: 1001
Name: Riya
Phone: 9876543210
Address: Delhi
Senior Citizen: No
Current Balance: 5000.0
================= BANK MENU =================
1. Open a Savings Bank Account
2. Deposit Money
3. Withdraw Money
4. Fixed Deposit (FD) Maturity Amount
5. Show Account Details
6. Exit
============================================
Enter your choice (1-6): 6
Thank you! Exiting program.
2. Participating in a quiz can be fun as it provides a competitive element. Some educational institutes use it as a tool to measure knowledge level, abilities and/or skills of their pupils either on a general level or in a specific field of study. Identify and analyse popular quiz shows and write a Python program to create a quiz that should also contain the following functionalities besides the one identified by you as a result of your analysis.
•
Create an administrative user ID and password to categorically add, modify, delete a question
•
Register the student before allowing her or him to play a quiz
•
Allow selection of category based on subject area
•
Display questions as per the chosen category
•
Keep the score as the participant plays
•
Display the final score
✅ Python Program (uses Dictionary + Tuple properly)
•
Dictionary is used to store:
•
Students (registration)
•
Question bank by category
•
Tuple (immutable) is used as a question record:
•
(question_text, options_tuple, correct_option_number)
Whenever we “modify” a question, we rebuild the tuple (because tuple is immutable).
"""
QUIZ SYSTEM (Class XI) - Tuples & Dictionaries
----------------------------------------------
Functionalities included:
1) Admin login (ID + password)
- Add/Modify/Delete questions category-wise
2) Student registration (must register before playing)
3) Category selection
4) Display questions from chosen category
5) Score tracking
6) Final score display
Data Structures:
- students (dict):
username -> (name, class_name, section) [tuple = immutable]
- quiz_bank (dict):
category -> dict of question_id -> question_tuple
- question_tuple (immutable tuple):
(question_text, options_tuple, correct_option_number)
"""
# ------------------ ADMIN CREDENTIALS (simple) ------------------
ADMIN_ID = "admin"
ADMIN_PASS = "1234"
# ------------------ STUDENT REGISTRATION STORAGE ------------------
# username -> (name, class_name, section)
students = {}
# ------------------ QUIZ QUESTION BANK ------------------
# category -> { qid -> (question_text, (opt1,opt2,opt3,opt4), correct_option_number) }
quiz_bank = {
"Python": {
1: ("Python is a ______ language.",
("low-level", "high-level", "machine", "assembly"),
2),
2: ("Which symbol is used for comments in Python?",
("//", "#", "/* */", ""),
2)
},
"Computer Basics": {
1: ("CPU stands for:",
("Central Processing Unit", "Computer Processing Unit", "Central Program Unit", "Control Processing Unit"),
1),
}
}
# To generate new question IDs category-wise
next_qid = {
"Python": 3,
"Computer Basics": 2
}
# ------------------ HELPER FUNCTIONS ------------------
def pause():
"""Small pause message to keep output readable."""
input("\nPress Enter to continue...")
def input_int(prompt, min_val=None, max_val=None):
"""Safely read an integer within optional bounds."""
while True:
try:
x = int(input(prompt))
if min_val is not None and x < min_val:
print("Enter a value >= " + str(min_val))
continue
if max_val is not None and x > max_val:
print("Enter a value <= " + str(max_val))
continue
return x
except ValueError:
print("Invalid input. Please enter an integer.")
def show_categories():
"""Display available categories."""
print("\nAvailable Categories:")
for i, cat in enumerate(quiz_bank.keys(), start=1):
print(str(i) + ". " + cat)
def get_category_by_number(num):
"""Return category name by selection number."""
categories = list(quiz_bank.keys())
if 1 <= num <= len(categories):
return categories[num - 1]
return None
# ------------------ ADMIN FUNCTIONS ------------------
def admin_login():
"""Admin login check."""
print("\n--- ADMIN LOGIN ---")
uid = input("Enter Admin ID: ").strip()
pwd = input("Enter Admin Password: ").strip()
if uid == ADMIN_ID and pwd == ADMIN_PASS:
print("✅ Admin Login Successful!")
return True
else:
print("❌ Invalid Admin Credentials!")
return False
def admin_add_question():
"""Add a new question to a chosen category."""
show_categories()
cat_no = input_int("Choose category number: ", 1, len(quiz_bank))
category = get_category_by_number(cat_no)
print("\n--- ADD QUESTION (Category: " + category + ") ---")
q_text = input("Enter question: ").strip()
options = []
for i in range(1, 5):
opt = input("Enter option " + str(i) + ": ").strip()
options.append(opt)
correct = input_int("Enter correct option number (1-4): ", 1, 4)
# Create immutable question tuple
q_tuple = (q_text, tuple(options), correct)
# Insert into dictionary using new qid
qid = next_qid.get(category, 1)
quiz_bank[category][qid] = q_tuple
next_qid[category] = qid + 1
print("✅ Question added with ID: " + str(qid))
def admin_list_questions(category):
"""List all questions in a category."""
print("\n--- QUESTIONS IN " + category + " ---")
if not quiz_bank[category]:
print("No questions available.")
return
for qid, qtuple in quiz_bank[category].items():
q_text, options_tuple, correct = qtuple
print("\nID: " + str(qid))
print("Q:", q_text)
for i, opt in enumerate(options_tuple, start=1):
print(" " + str(i) + ". " + opt)
print("(Correct option stored as:", correct, ")") # admin can see for checking
def admin_modify_question():
"""Modify an existing question (rebuild tuple)."""
show_categories()
cat_no = input_int("Choose category number: ", 1, len(quiz_bank))
category = get_category_by_number(cat_no)
admin_list_questions(category)
qid = input_int("\nEnter Question ID to modify: ")
if qid not in quiz_bank[category]:
print("❌ Question ID not found.")
return
old_q = quiz_bank[category][qid]
print("\nEditing Question:", old_q[0])
new_q_text = input("Enter new question text (or press Enter to keep same): ").strip()
if new_q_text == "":
new_q_text = old_q[0]
# Options
old_options = old_q[1]
new_options = []
for i in range(4):
entered = input("Option " + str(i + 1) + " (current: " + old_options[i] + "): ").strip()
if entered == "":
new_options.append(old_options[i])
else:
new_options.append(entered)
new_correct = input("Correct option number 1-4 (press Enter to keep same): ").strip()
if new_correct == "":
new_correct = old_q[2]
else:
new_correct = int(new_correct)
if new_correct < 1 or new_correct > 4:
print("Invalid correct option. Keeping old value.")
new_correct = old_q[2]
# Rebuild immutable tuple
quiz_bank[category][qid] = (new_q_text, tuple(new_options), new_correct)
print("✅ Question modified successfully.")
def admin_delete_question():
"""Delete a question from a category."""
show_categories()
cat_no = input_int("Choose category number: ", 1, len(quiz_bank))
category = get_category_by_number(cat_no)
admin_list_questions(category)
qid = input_int("\nEnter Question ID to delete: ")
if qid in quiz_bank[category]:
del quiz_bank[category][qid]
print("✅ Question deleted successfully.")
else:
print("❌ Question ID not found.")
def admin_menu():
"""Admin operations menu."""
while True:
print("\n========== ADMIN MENU ==========")
print("1. Add Question")
print("2. Modify Question")
print("3. Delete Question")
print("4. List Questions")
print("5. Back to Main Menu")
print("================================")
choice = input_int("Enter choice (1-5): ", 1, 5)
if choice == 1:
admin_add_question()
pause()
elif choice == 2:
admin_modify_question()
pause()
elif choice == 3:
admin_delete_question()
pause()
elif choice == 4:
show_categories()
cat_no = input_int("Choose category number: ", 1, len(quiz_bank))
category = get_category_by_number(cat_no)
admin_list_questions(category)
pause()
else:
break
# ------------------ STUDENT FUNCTIONS ------------------
def register_student():
"""Register student before quiz."""
print("\n--- STUDENT REGISTRATION ---")
username = input("Create a username: ").strip()
if username in students:
print("❌ Username already exists. Try a different username.")
return
name = input("Enter full name: ").strip()
class_name = input("Enter class (e.g., X): ").strip()
section = input("Enter section (e.g., A): ").strip()
# Store as immutable tuple
students[username] = (name, class_name, section)
print("✅ Registration successful!")
def login_student():
"""Simple login by username (for school level)."""
print("\n--- STUDENT LOGIN ---")
username = input("Enter your username: ").strip()
if username in students:
print("✅ Login successful!")
return username
else:
print("❌ Not registered. Please register first.")
return None
def play_quiz(username):
"""
Play quiz:
- choose category
- show questions
- keep score
- show final score
"""
show_categories()
cat_no = input_int("Choose category number to play: ", 1, len(quiz_bank))
category = get_category_by_number(cat_no)
questions = quiz_bank[category]
if not questions:
print("No questions available in this category.")
return
print("\n--- QUIZ STARTED (Category: " + category + ") ---")
print("Student:", students[username][0])
score = 0
total = len(questions)
# Ask questions in sorted order of IDs
for qid in sorted(questions.keys()):
q_text, options_tuple, correct = questions[qid]
print("\n--------------------------------")
print("Q" + str(qid) + ". " + q_text)
for i, opt in enumerate(options_tuple, start=1):
print(str(i) + ". " + opt)
ans = input_int("Enter your answer (1-4): ", 1, 4)
if ans == correct:
print("✅ Correct!")
score += 1
else:
print("❌ Wrong!")
print("Correct answer was:", correct)
print("\n========== FINAL SCORE ==========")
print("Student:", students[username][0])
print("Category:", category)
print("Score:", score, "/", total)
print("================================")
def student_menu():
"""Student menu to register/login/play."""
while True:
print("\n========== STUDENT MENU ==========")
print("1. Register")
print("2. Login and Play Quiz")
print("3. Back to Main Menu")
print("=================================")
choice = input_int("Enter choice (1-3): ", 1, 3)
if choice == 1:
register_student()
pause()
elif choice == 2:
user = login_student()
if user:
play_quiz(user)
pause()
else:
break
# ------------------ MAIN MENU ------------------
def main():
while True:
print("\n============= QUIZ SYSTEM =============")
print("1. Admin Login")
print("2. Student Panel")
print("3. Exit")
print("=======================================")
choice = input_int("Enter choice (1-3): ", 1, 3)
if choice == 1:
if admin_login():
admin_menu()
pause()
elif choice == 2:
student_menu()
else:
print("Thank you! Exiting.")
break
# Run program
main()
✅ Sample Output (Example Run)
1) Student registers and plays Python category
============= QUIZ SYSTEM =============
1. Admin Login
2. Student Panel
3. Exit
Enter choice (1-3): 2
========== STUDENT MENU ==========
1. Register
2. Login and Play Quiz
3. Back to Main Menu
Enter choice (1-3): 1
--- STUDENT REGISTRATION ---
Create a username: stu1
Enter full name: Ananya Sharma
Enter class (e.g., X): X
Enter section (e.g., A): A
✅ Registration successful!
Press Enter to continue...
========== STUDENT MENU ==========
Enter choice (1-3): 2
--- STUDENT LOGIN ---
Enter your username: stu1
✅ Login successful!
Available Categories:
1. Python
2. Computer Basics
Choose category number to play: 1
--- QUIZ STARTED (Category: Python) ---
Student: Ananya Sharma
--------------------------------
Q1. Python is a ______ language.
1. low-level
2. high-level
3. machine
4. assembly
Enter your answer (1-4): 2
✅ Correct!
--------------------------------
Q2. Which symbol is used for comments in Python?
1. //
2. #
3. /* */
4.
Enter your answer (1-4): 2
✅ Correct!
========== FINAL SCORE ==========
Student: Ananya Sharma
Category: Python
Score: 2 / 2
================================
2) Admin adds a question (sample)
============= QUIZ SYSTEM =============
1. Admin Login
2. Student Panel
3. Exit
Enter choice (1-3): 1
--- ADMIN LOGIN ---
Enter Admin ID: admin
Enter Admin Password: 1234
✅ Admin Login Successful!
========== ADMIN MENU ==========
1. Add Question
2. Modify Question
3. Delete Question
4. List Questions
5. Back to Main Menu
Enter choice (1-5): 1
Available Categories:
1. Python
2. Computer Basics
Choose category number: 1
--- ADD QUESTION (Category: Python) ---
Enter question: What is the output of print(2+3)?
Enter option 1: 23
Enter option 2: 5
Enter option 3: 6
Enter option 4: 2+3
Enter correct option number (1-4): 2
✅ Question added with ID: 3
3. Our heritage monuments are our assets. They are a reflection of our rich and glorious past and an inspiration for our future. UNESCO has identified some of Indian heritage sites as World heritage sites. Collect the following information about these sites:
•
What is the name of the site?
•
Where is it located?
•
District
•
State
•
When was it built?
•
Who built it?
•
Why was it built?
•
Website link (if any).
Write a Python program to
•
create an administrative user ID and password to add, modify or delete an entered heritage site in the list of sites
•
display the list of world heritage sites in India
•
search and display information of a world heritage site entered by the user
•
display the name(s) of world heritage site(s) on the basis of the state input by the user.
Below is a Tuples + Dictionaries based solution for the Heritage Sites case study.
I’m using a dictionary to store the sites, and each site’s information is stored as an immutable tuple (so when we “modify”, we rebuild the tuple — exactly what this chapter wants).
I’ve also filled a starter list of 4 realistic UNESCO Indian sites with correct details (you can add more).
✅ Python Program: World Heritage Sites in India (Admin CRUD + Search + Filter)
"""
HERITAGE SITES (Tuples & Dictionaries) - Class XI
------------------------------------------------
Required features:
1) Admin ID/password to Add/Modify/Delete a site
2) Display list of World Heritage Sites in India
3) Search and display info of a site (by name)
4) Display site name(s) by State
Data Structures:
- heritage_sites: dict
key -> site name (string)
value -> immutable tuple:
(district, state, built_when, built_by, why_built, website)
Tuple is immutable, so for MODIFY we rebuild a new tuple and replace it.
"""
# ------------------ ADMIN CREDENTIALS ------------------
ADMIN_ID = "admin"
ADMIN_PASS = "1234"
# Tuple field indexes (so code stays readable)
IDX_DISTRICT = 0
IDX_STATE = 1
IDX_BUILT = 2
IDX_BUILTBY = 3
IDX_WHY = 4
IDX_WEB = 5
# ------------------ STARTER DATA (sample UNESCO sites) ------------------
# key = Site Name
# value = (District, State, When built, Who built, Why built, Website)
heritage_sites = {
"Taj Mahal": (
"Agra",
"Uttar Pradesh",
"1632–1648 (main mausoleum), with other parts completed later",
"Mughal Emperor Shah Jahan",
"Built in memory of his wife Mumtaz Mahal",
"https://whc.unesco.org/en/list/252/"
),
"Qutb Minar and its Monuments": (
"South Delhi (Mehrauli)",
"Delhi",
"Started 1199 and largely completed around 1220 (early 13th century)",
"Qutb-ud-din Aibak; later completed by Iltutmish",
"Victory tower / marks beginning of Islamic rule in the region",
"https://whc.unesco.org/en/list/233/"
),
"Sun Temple, Konark": (
"Puri",
"Odisha",
"13th century (c. 1250)",
"King Narasimhadeva I (Eastern Ganga dynasty)",
"Built as a grand temple dedicated to the Sun God (Surya)",
"https://whc.unesco.org/en/list/246/"
),
"Ajanta Caves": (
"Aurangabad",
"Maharashtra",
"2nd–1st century BCE and 5th–6th century CE (in phases)",
"Buddhist monastic communities with royal/wealthy patronage",
"Rock-cut Buddhist monasteries and prayer halls; created for Buddhist religious life and art",
"https://whc.unesco.org/en/list/242/"
),
}
# ------------------ HELPER FUNCTIONS ------------------
def normalize_name(name):
"""Helps match names even if user types different cases/spaces."""
return " ".join(name.strip().split())
def print_site_details(site_name, site_tuple):
"""Print site details neatly."""
print("\n----------------------------------------")
print("Site Name :", site_name)
print("District :", site_tuple[IDX_DISTRICT])
print("State :", site_tuple[IDX_STATE])
print("Built :", site_tuple[IDX_BUILT])
print("Built By :", site_tuple[IDX_BUILTBY])
print("Why Built :", site_tuple[IDX_WHY])
print("Website :", site_tuple[IDX_WEB])
print("----------------------------------------")
def admin_login():
"""Simple admin authentication."""
print("\n--- ADMIN LOGIN ---")
uid = input("Admin ID: ").strip()
pwd = input("Password: ").strip()
return uid == ADMIN_ID and pwd == ADMIN_PASS
def rebuild_site_tuple(old_tuple, district, state, built_when, built_by, why_built, website):
"""
Create a NEW tuple (immutable) with updated values.
This shows tuple immutability: we rebuild the tuple.
"""
return (district, state, built_when, built_by, why_built, website)
# ------------------ REQUIRED FEATURES ------------------
def display_all_sites():
"""Display the list of all sites (names only)."""
print("\n========== WORLD HERITAGE SITES (IN DATA) ==========")
if not heritage_sites:
print("No sites available.")
return
for i, name in enumerate(sorted(heritage_sites.keys()), start=1):
print(str(i) + ". " + name)
print("===================================================")
def search_site():
"""Search and display info of a site entered by the user."""
name = normalize_name(input("\nEnter site name to search: "))
if name in heritage_sites:
print_site_details(name, heritage_sites[name])
else:
print("❌ Site not found. Please check spelling or view the list.")
def sites_by_state():
"""Display site name(s) based on state entered by user."""
state_in = normalize_name(input("\nEnter State name: "))
matches = []
for site_name, site_tuple in heritage_sites.items():
if normalize_name(site_tuple[IDX_STATE]).lower() == state_in.lower():
matches.append(site_name)
print("\n========== SITES IN STATE ==========")
if matches:
for s in sorted(matches):
print("-", s)
else:
print("No site found in this state (in current data).")
print("====================================")
# ------------------ ADMIN CRUD ------------------
def admin_add_site():
"""Admin: add a new heritage site."""
print("\n--- ADD NEW SITE ---")
name = normalize_name(input("Site Name: "))
if name in heritage_sites:
print("❌ Site already exists. Use Modify instead.")
return
district = input("District: ").strip()
state = input("State: ").strip()
built_when = input("When was it built?: ").strip()
built_by = input("Who built it?: ").strip()
why_built = input("Why was it built?: ").strip()
website = input("Website link (if any): ").strip()
heritage_sites[name] = (district, state, built_when, built_by, why_built, website)
print("✅ Site added successfully.")
def admin_modify_site():
"""Admin: modify an existing site (rebuild tuple)."""
print("\n--- MODIFY SITE ---")
name = normalize_name(input("Enter site name to modify: "))
if name not in heritage_sites:
print("❌ Site not found.")
return
old = heritage_sites[name]
print("\n(Press Enter to keep the old value)")
district = input("District [" + old[IDX_DISTRICT] + "]: ").strip() or old[IDX_DISTRICT]
state = input("State [" + old[IDX_STATE] + "]: ").strip() or old[IDX_STATE]
built_when = input("Built When [" + old[IDX_BUILT] + "]: ").strip() or old[IDX_BUILT]
built_by = input("Built By [" + old[IDX_BUILTBY] + "]: ").strip() or old[IDX_BUILTBY]
why_built = input("Why Built [" + old[IDX_WHY] + "]: ").strip() or old[IDX_WHY]
website = input("Website [" + old[IDX_WEB] + "]: ").strip() or old[IDX_WEB]
# rebuild immutable tuple
heritage_sites[name] = rebuild_site_tuple(old, district, state, built_when, built_by, why_built, website)
print("✅ Site modified successfully.")
def admin_delete_site():
"""Admin: delete a site."""
print("\n--- DELETE SITE ---")
name = normalize_name(input("Enter site name to delete: "))
if name in heritage_sites:
del heritage_sites[name]
print("✅ Site deleted successfully.")
else:
print("❌ Site not found.")
def admin_menu():
"""Admin operations menu."""
while True:
print("\n========== ADMIN MENU ==========")
print("1. Add Site")
print("2. Modify Site")
print("3. Delete Site")
print("4. Display All Sites")
print("5. Back to Main Menu")
print("================================")
choice = input("Enter choice (1-5): ").strip()
if choice == "1":
admin_add_site()
elif choice == "2":
admin_modify_site()
elif choice == "3":
admin_delete_site()
elif choice == "4":
display_all_sites()
elif choice == "5":
break
else:
print("Invalid choice.")
# ------------------ MAIN MENU ------------------
def main():
while True:
print("\n========== WORLD HERITAGE SITES (INDIA) ==========")
print("1. Admin Login (Add/Modify/Delete)")
print("2. Display List of Sites")
print("3. Search a Site and Display Information")
print("4. Display Sites by State")
print("5. Exit")
print("=================================================")
ch = input("Enter choice (1-5): ").strip()
if ch == "1":
if admin_login():
print("✅ Admin login successful.")
admin_menu()
else:
print("❌ Invalid admin credentials.")
elif ch == "2":
display_all_sites()
elif ch == "3":
search_site()
elif ch == "4":
sites_by_state()
elif ch == "5":
print("Thank you! Exiting.")
break
else:
print("Invalid choice.")
# Run the program
main()
✅ Sample Output (Example Run)
1) Display list
========== WORLD HERITAGE SITES (INDIA) ==========
1. Admin Login (Add/Modify/Delete)
2. Display List of Sites
3. Search a Site and Display Information
4. Display Sites by State
5. Exit
=================================================
Enter choice (1-5): 2
========== WORLD HERITAGE SITES (IN DATA) ==========
1. Ajanta Caves
2. Qutb Minar and its Monuments
3. Sun Temple, Konark
4. Taj Mahal
===================================================
2) Search “Taj Mahal”
========== WORLD HERITAGE SITES (INDIA) ==========
1. Admin Login (Add/Modify/Delete)
2. Display List of Sites
3. Search a Site and Display Information
4. Display Sites by State
5. Exit
=================================================
Enter choice (1-5): 3
Enter site name to search: Taj Mahal
----------------------------------------
Site Name : Taj Mahal
District : Agra
State : Uttar Pradesh
Built : 1632–1648 (main mausoleum), with other parts completed later
Built By : Mughal Emperor Shah Jahan
Why Built : Built in memory of his wife Mumtaz Mahal
Website : https://whc.unesco.org/en/list/252/
----------------------------------------
3) Filter by state “Odisha”
========== WORLD HERITAGE SITES (INDIA) ==========
1. Admin Login (Add/Modify/Delete)
2. Display List of Sites
3. Search a Site and Display Information
4. Display Sites by State
5. Exit
=================================================
Enter choice (1-5): 4
Enter State name: Odisha
========== SITES IN STATE ==========
- Sun Temple, Konark
====================================
4) Admin modifies a site (tuple rebuild)
========== WORLD HERITAGE SITES (INDIA) ==========
1. Admin Login (Add/Modify/Delete)
2. Display List of Sites
3. Search a Site and Display Information
4. Display Sites by State
5. Exit
=================================================
Enter choice (1-5): 1
--- ADMIN LOGIN ---
Admin ID: admin
Password: 1234
✅ Admin login successful.
Enter choice (1-5): 2
--- MODIFY SITE ---
Enter site name to modify: Ajanta Caves
(Press Enter to keep the old value)
District [Aurangabad]:
State [Maharashtra]:
Built When [2nd–1st century BCE and 5th–6th century CE (in phases)]:
Built By [Buddhist monastic communities with royal/wealthy patronage]:
Why Built [Rock-cut Buddhist monasteries and prayer halls; created for Buddhist religious life and art]:
Website [https://whc.unesco.org/en/list/242/]:
✅ Site modified successfully.
5) Admin adds a new site
========== WORLD HERITAGE SITES (INDIA) ==========
1. Admin Login (Add/Modify/Delete)
2. Display List of Sites
3. Search a Site and Display Information
4. Display Sites by State
5. Exit
=================================================
Enter choice (1-5): 1
--- ADMIN LOGIN ---
Admin ID: admin
Password: 1234
✅ Admin login successful.
Enter choice (1-5): 1
--- ADD NEW SITE ---
Site Name: Hampi
District: Vijayanagara
State: Karnataka
When was it built?: 14th–16th century
Who built it?: Vijayanagara Empire
Why was it built?: Capital city with temples and monuments
Website link (if any): https://whc.unesco.org/en/list/241/
✅ Site added successfully.
4. Every mode of transport utilises a reservation system to ensure its smooth and efficient functioning. If you analyse you would find many things in common. You are required to identify any one mode of transportation and prepare a reservation system for it. For example, let us look at the Railway reservation system we talked about earlier. The complex task of designing a good railway reservation system is seen as designing the different components of the system and then making them work with each other efficiently. Possible sub-systems are shown in Figure 1. Each of them may be modelled using functions.
Write a python code to automate the reservation needs of the identified mode of transport.
✅ Python Program (Railway Reservation System using Tuples + Dictionaries)
How tuples & dictionaries are used (important for this chapter)
•
trains is a dictionary: train_no -> train_tuple (immutable)•
bookings is a dictionary: PNR -> booking_tuple (immutable)•
When we need to change seats/bookings, we rebuild tuples (since tuples are immutable).
"""
RAILWAY RESERVATION SYSTEM (Tuples & Dictionaries)
------------------------------------------------------------
Subsystems modelled using functions (as per Figure idea):
1) Enquiry / Availability
2) Reservation (Booking)
3) Cancellation
4) Ticket display
5) Chart / Passenger list
6) Admin (add/modify/delete trains)
This is a simplified school-level model:
- Seat counts are stored per class (SL, 3A, 2A)
- Booking reduces availability; cancellation restores it
- No real payment gateway (just simulated)
"""
# ---------------------- ADMIN CREDENTIALS ----------------------
ADMIN_ID = "admin"
ADMIN_PASS = "1234"
# ---------------------- DATA STRUCTURES -----------------------
# Train record is an IMMUTABLE tuple:
# (train_no, train_name, source, destination, classes_dict)
# classes_dict is a dictionary like {"SL": 50, "3A": 20, "2A": 10}
# We'll store trains in a dictionary:
# trains[train_no] = train_tuple
trains = {
12701: (12701, "Intercity Express", "Hyderabad", "Vijayawada", {"SL": 50, "3A": 20, "2A": 10}),
12015: (12015, "Shatabdi Express", "Bengaluru", "Chennai", {"CC": 60, "EC": 20}),
}
# Booking record is an IMMUTABLE tuple:
# (pnr, passenger_name, age, train_no, class_code, seats, status)
# status: "CONFIRMED" or "CANCELLED"
# bookings[pnr] = booking_tuple
bookings = {}
next_pnr = 1000001 # simple PNR generator
# ---------------------- INDEX CONSTANTS -----------------------
# Train tuple indexes
T_NO = 0
T_NAME = 1
T_SRC = 2
T_DST = 3
T_CLASSES = 4
# Booking tuple indexes
B_PNR = 0
B_NAME = 1
B_AGE = 2
B_TRAIN = 3
B_CLASS = 4
B_SEATS = 5
B_STATUS = 6
# ---------------------- HELPER FUNCTIONS ----------------------
def admin_login():
"""Checks admin credentials."""
uid = input("Admin ID: ").strip()
pwd = input("Password: ").strip()
return uid == ADMIN_ID and pwd == ADMIN_PASS
def rebuild_train_tuple(old_train_tuple, new_classes_dict):
"""
Rebuild a NEW train tuple with updated seat availability (tuple is immutable).
"""
return (
old_train_tuple[T_NO],
old_train_tuple[T_NAME],
old_train_tuple[T_SRC],
old_train_tuple[T_DST],
new_classes_dict
)
def rebuild_booking_tuple(old_booking_tuple, new_status):
"""Rebuild a NEW booking tuple with updated status."""
return (
old_booking_tuple[B_PNR],
old_booking_tuple[B_NAME],
old_booking_tuple[B_AGE],
old_booking_tuple[B_TRAIN],
old_booking_tuple[B_CLASS],
old_booking_tuple[B_SEATS],
new_status
)
def show_all_trains():
"""Displays all trains (Enquiry list)."""
print("\n========== AVAILABLE TRAINS ==========")
if not trains:
print("No trains available.")
return
for tno in sorted(trains.keys()):
t = trains[tno]
print(format(t[T_NO]) + " - " + t[T_NAME] + " (" + t[T_SRC] + " -> " + t[T_DST] + ")")
print("=====================================")
def show_train_details(train_no):
"""Displays complete info of a train including seat availability."""
if train_no not in trains:
print("❌ Train not found.")
return
t = trains[train_no]
print("\n-------------------------------------")
print("Train No :", t[T_NO])
print("Train Name :", t[T_NAME])
print("Route :", t[T_SRC], "->", t[T_DST])
print("Availability :")
for cls, seats in t[T_CLASSES].items():
print(" " + cls + ": " + format(seats) + " seats")
print("-------------------------------------")
# ---------------------- SUBSYSTEM 1: ENQUIRY / SEARCH ----------------------
def search_trains_by_route():
"""Search trains by source & destination."""
src = input("Enter Source: ").strip()
dst = input("Enter Destination: ").strip()
found = False
print("\n========== SEARCH RESULTS ==========")
for tno, t in trains.items():
if t[T_SRC].lower() == src.lower() and t[T_DST].lower() == dst.lower():
print(format(t[T_NO]) + " - " + t[T_NAME])
found = True
if not found:
print("No trains found for this route.")
print("===================================")
def check_availability():
"""Check seat availability for a selected train."""
train_no = int(input("Enter Train Number: "))
show_train_details(train_no)
# ---------------------- SUBSYSTEM 2: RESERVATION (BOOK TICKET) ----------------------
def book_ticket():
"""
Book a ticket:
- choose train
- choose class
- enter passenger details
- reduce seat availability
- create booking with PNR
"""
global next_pnr
train_no = int(input("Enter Train Number to book: "))
if train_no not in trains:
print("❌ Train not found.")
return
t = trains[train_no]
classes = t[T_CLASSES]
print("\nAvailable Classes:", ", ".join(classes.keys()))
cls = input("Enter class code (example SL/3A/2A/CC/EC): ").strip()
if cls not in classes:
print("❌ Invalid class.")
return
seats_needed = int(input("How many seats? "))
if seats_needed <= 0:
print("Seats must be at least 1.")
return
available = classes[cls]
if seats_needed > available:
print("❌ Not enough seats available.")
print("Available seats in", cls, ":", available)
return
# Passenger details
name = input("Passenger Name: ").strip()
age = int(input("Age: "))
# Reduce availability: rebuild classes dict and train tuple
new_classes = dict(classes) # copy
new_classes[cls] = available - seats_needed
trains[train_no] = rebuild_train_tuple(t, new_classes)
# Create booking tuple (immutable)
pnr = next_pnr
next_pnr += 1
booking = (pnr, name, age, train_no, cls, seats_needed, "CONFIRMED")
bookings[pnr] = booking
print("\n✅ Booking Confirmed!")
print("PNR:", pnr)
print("Train:", t[T_NAME])
print("Class:", cls, "|", "Seats:", seats_needed)
# ---------------------- SUBSYSTEM 3: CANCELLATION ----------------------
def cancel_ticket():
"""
Cancel a ticket using PNR:
- mark booking status CANCELLED (rebuild tuple)
- restore seat availability in train
"""
pnr = int(input("Enter PNR to cancel: "))
if pnr not in bookings:
print("❌ PNR not found.")
return
b = bookings[pnr]
if b[B_STATUS] == "CANCELLED":
print("Ticket already cancelled.")
return
train_no = b[B_TRAIN]
cls = b[B_CLASS]
seats = b[B_SEATS]
# Restore seats in train
t = trains[train_no]
classes = t[T_CLASSES]
new_classes = dict(classes)
new_classes[cls] = new_classes.get(cls, 0) + seats
trains[train_no] = rebuild_train_tuple(t, new_classes)
# Update booking status (rebuild tuple)
bookings[pnr] = rebuild_booking_tuple(b, "CANCELLED")
print("✅ Ticket cancelled successfully.")
# ---------------------- SUBSYSTEM 4: DISPLAY TICKET ----------------------
def print_ticket():
"""Display booking info using PNR."""
pnr = int(input("Enter PNR: "))
if pnr not in bookings:
print("❌ PNR not found.")
return
b = bookings[pnr]
t = trains[b[B_TRAIN]]
print("\n========== TICKET ==========")
print("PNR :", b[B_PNR])
print("Status :", b[B_STATUS])
print("Passenger :", b[B_NAME], "|", "Age:", b[B_AGE])
print("Train :", t[T_NO], "-", t[T_NAME])
print("Route :", t[T_SRC], "->", t[T_DST])
print("Class :", b[B_CLASS])
print("Seats :", b[B_SEATS])
print("=============================")
# ---------------------- SUBSYSTEM 5: CHART / PASSENGER LIST ----------------------
def show_chart_for_train():
"""
Display list of CONFIRMED passengers for a train.
(Simple charting subsystem)
"""
train_no = int(input("Enter Train Number for chart: "))
if train_no not in trains:
print("❌ Train not found.")
return
print("\n========== PASSENGER CHART ==========")
print("Train:", trains[train_no][T_NAME])
found = False
for pnr, b in bookings.items():
if b[B_TRAIN] == train_no and b[B_STATUS] == "CONFIRMED":
print("PNR " + format(pnr) + " | " + b[B_NAME] + " | Age " + format(b[B_AGE]) + " | " + b[B_CLASS] + " | Seats " + format(b[B_SEATS]))
found = True
if not found:
print("No confirmed passengers for this train.")
print("=====================================")
# ---------------------- SUBSYSTEM 6: ADMIN (ADD/MODIFY/DELETE TRAIN) ----------------------
def admin_add_train():
"""Add a new train."""
tno = int(input("Enter new Train Number: "))
if tno in trains:
print("❌ Train number already exists.")
return
name = input("Train Name: ").strip()
src = input("Source: ").strip()
dst = input("Destination: ").strip()
# Enter classes and seats
class_dict = {}
count = int(input("How many classes (example: 2 for SL and 3A)? "))
for _ in range(count):
cls = input("Class code: ").strip()
seats = int(input("Seats available: "))
class_dict[cls] = seats
trains[tno] = (tno, name, src, dst, class_dict)
print("✅ Train added successfully.")
def admin_delete_train():
"""Delete a train."""
tno = int(input("Enter Train Number to delete: "))
if tno in trains:
del trains[tno]
print("✅ Train deleted.")
else:
print("❌ Train not found.")
def admin_menu():
"""Admin menu for maintenance subsystem."""
while True:
print("\n========== ADMIN MENU ==========")
print("1. Add Train")
print("2. Delete Train")
print("3. View All Trains")
print("4. Back")
ch = input("Enter choice: ").strip()
if ch == "1":
admin_add_train()
elif ch == "2":
admin_delete_train()
elif ch == "3":
show_all_trains()
elif ch == "4":
break
else:
print("Invalid choice.")
# ---------------------- MAIN MENU ----------------------
def main():
while True:
print("\n============= RAILWAY RESERVATION SYSTEM =============")
print("1. Display All Trains (Enquiry)")
print("2. Search Trains by Route")
print("3. Check Availability")
print("4. Book Ticket (Reservation)")
print("5. Cancel Ticket")
print("6. Print Ticket")
print("7. Show Passenger Chart")
print("8. Admin Login (Maintenance)")
print("9. Exit")
print("======================================================")
choice = input("Enter choice (1-9): ").strip()
if choice == "1":
show_all_trains()
elif choice == "2":
search_trains_by_route()
elif choice == "3":
check_availability()
elif choice == "4":
book_ticket()
elif choice == "5":
cancel_ticket()
elif choice == "6":
print_ticket()
elif choice == "7":
show_chart_for_train()
elif choice == "8":
print("\n--- ADMIN LOGIN ---")
if admin_login():
print("✅ Admin login successful.")
admin_menu()
else:
print("❌ Invalid admin credentials.")
elif choice == "9":
print("Thank you! Exiting.")
break
else:
print("Invalid choice. Please enter 1-9.")
# Run the program
main()
Sample Output
1) Display trains
============= RAILWAY RESERVATION SYSTEM =============
1. Display All Trains (Enquiry)
2. Search Trains by Route
3. Check Availability
4. Book Ticket (Reservation)
5. Cancel Ticket
6. Print Ticket
7. Show Passenger Chart
8. Admin Login (Maintenance)
9. Exit
======================================================
Enter choice (1-9): 1
========== AVAILABLE TRAINS ==========
12015 - Shatabdi Express (Bengaluru -> Chennai)
12701 - Intercity Express (Hyderabad -> Vijayawada)
=====================================
Sample Output
2) Check availability
============= RAILWAY RESERVATION SYSTEM =============
1. Display All Trains (Enquiry)
2. Search Trains by Route
3. Check Availability
4. Book Ticket (Reservation)
5. Cancel Ticket
6. Print Ticket
7. Show Passenger Chart
8. Admin Login (Maintenance)
9. Exit
======================================================
Enter choice (1-9): 3
Enter Train Number: 12701
-------------------------------------
Train No : 12701
Train Name : Intercity Express
Route : Hyderabad -> Vijayawada
Availability :
SL: 50 seats
3A: 20 seats
2A: 10 seats
-------------------------------------
Sample Output
3) Book ticket (Reservation)
============= RAILWAY RESERVATION SYSTEM =============
1. Display All Trains (Enquiry)
2. Search Trains by Route
3. Check Availability
4. Book Ticket (Reservation)
5. Cancel Ticket
6. Print Ticket
7. Show Passenger Chart
8. Admin Login (Maintenance)
9. Exit
======================================================
Enter choice (1-9): 4
Enter Train Number to book: 12701
Available Classes: SL, 3A, 2A
Enter class code (example SL/3A/2A/CC/EC): SL
How many seats? 2
Passenger Name: Ananya Sharma
Age: 16
✅ Booking Confirmed!
PNR: 1000001
Train: Intercity Express
Class: SL | Seats: 2
Sample Output
4) Print Ticket
============= RAILWAY RESERVATION SYSTEM =============
1. Display All Trains (Enquiry)
2. Search Trains by Route
3. Check Availability
4. Book Ticket (Reservation)
5. Cancel Ticket
6. Print Ticket
7. Show Passenger Chart
8. Admin Login (Maintenance)
9. Exit
======================================================
Enter choice (1-9): 6
Enter PNR: 1000001
========== TICKET ==========
PNR : 1000001
Status : CONFIRMED
Passenger : Ananya Sharma | Age: 16
Train : 12701 - Intercity Express
Route : Hyderabad -> Vijayawada
Class : SL
Seats : 2
============================
Sample Output
5) Show Chart (Passenger list)
============= RAILWAY RESERVATION SYSTEM =============
1. Display All Trains (Enquiry)
2. Search Trains by Route
3. Check Availability
4. Book Ticket (Reservation)
5. Cancel Ticket
6. Print Ticket
7. Show Passenger Chart
8. Admin Login (Maintenance)
9. Exit
======================================================
Enter choice (1-9): 7
Enter Train Number for chart: 12701
========== PASSENGER CHART ==========
Train: Intercity Express
PNR 1000001 | Ananya Sharma | Age 16 | SL | Seats 2
====================================
Sample Output
6) Cancel ticket
============= RAILWAY RESERVATION SYSTEM =============
1. Display All Trains (Enquiry)
2. Search Trains by Route
3. Check Availability
4. Book Ticket (Reservation)
5. Cancel Ticket
6. Print Ticket
7. Show Passenger Chart
8. Admin Login (Maintenance)
9. Exit
======================================================
Enter choice (1-9): 5
Enter PNR to cancel: 1000001
✅ Ticket cancelled successfully.