0% found this document useful (0 votes)
3 views15 pages

Experiment 05 Python

The document outlines various programming exercises involving lists, tuples, dictionaries, and their applications in Python. It includes detailed theories, code snippets, and expected outputs for tasks such as counting occurrences of values, calculating averages, finding runner-up scores, managing movie details, creating a contact book, and managing a todo list. Each exercise emphasizes the use of specific data structures to efficiently handle and manipulate data.

Uploaded by

arpan2007dey
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views15 pages

Experiment 05 Python

The document outlines various programming exercises involving lists, tuples, dictionaries, and their applications in Python. It includes detailed theories, code snippets, and expected outputs for tasks such as counting occurrences of values, calculating averages, finding runner-up scores, managing movie details, creating a contact book, and managing a todo list. Each exercise emphasizes the use of specific data structures to efficiently handle and manipulate data.

Uploaded by

arpan2007dey
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Name : Arpan Dey

Sap_Id : 590024562
Batch : 01

Experiment No 5 - [Lists, tuples, dictionary

Date-: [6-02-2026]

QUESTION1 : Scan n values in range 0-3 and print the number of times each value has
occurred.

THEORY :- This problem involves scanning n input values where each value is
restricted to a fixed range (0–3) and counting how many times each value
occurs. Since the range of possible values is small and known in advance, we
can use a counting technique (also called frequency counting) instead of
complex data structures. We initialize counters for each possible value (0, 1, 2,
and 3) and then read the n inputs one by one. For every input value, the
corresponding counter is incremented. After all values are scanned, the final
counts represent the frequency (number of occurrences) of each value. This
method is efficient, easy to implement, and avoids unnecessary loops or
searches, making it ideal for problems involving limited-range data
classification.

CODE :- n = int(input("Enter the number of values to scan: ")) count =

[0,0,0,0]

for i in range(n):

val = int(input(f"Enter value {i+1} (0-3): "))

if 0 <= val <= 3: count[val] += 1 else:

print("Value out of range, please enter a value between 0 and 3.")


for i in

range(4):

print(f"Number of times {i} occurred: {count[i]}")

OUTPUT :-

QUESTION 2 - Create a tuple to store n numeric values and find average of all
values.
THEORY - In this problem, a tuple is used to store n numeric values,
emphasizing the concept of immutability, meaning that once values are stored in
a tuple, they cannot be changed. The user inputs n numbers, which are collected
and converted into a tuple for safe, fixed storage. To find the average, all the
values in the tuple are added together to compute their total sum, and this sum is
then divided by the total number of values (n). This approach demonstrates how
tuples can be used for secure data storage while still allowing mathematical
operations such as summation and averaging through iteration or built-in
functions. It also highlights the importance of basic data aggregation techniques
in programming.

CODE - n = int(input("Enter the number of numeric values: "))


values = [] for i in range(n):
val = float(input(f"Enter value {i+1}: "))
[Link](val) values_tuple =
tuple(values) average =
sum(values_tuple) / n
print("The average of the given values is:", average)

OUTPUT :-

QUESTION – 3 WAP to input a list of scores for N students in a list data type.
Find the score of the runner up and print the output. Sample Input N = 5
Scores= 2 3 6 6 5 Sample output 5
THEORY - This program involves storing the scores of N students in a list
data type and finding the runner-up score, which is the second highest distinct
value in the list. Since multiple students can have the same score, duplicate
values must be handled properly by removing repetitions before determining
rankings. The process typically involves scanning the list, identifying the
maximum score, removing all occurrences of that maximum value, and then
finding the next highest value from the remaining scores. This approach
demonstrates the use of list operations, conditional logic, and data filtering
concepts in Python. It also highlights how lists can efficiently manage
collections of data while enabling ranking, comparison, and aggregation
operations.

CODE - n = int(input("Enter the number of students: "))

scores = list(map(int, input("Enter the scores for the students: ").split() ))


scores = list (set(scores)) [Link]()
print("The runner-up score is:", scores[-2])

OUTPUT :-

QUESTION – 4 Create a dictionary of n persons where key is name and


value is city. a) Display all names b) Display all city names c) Display
student name and city of all students. d) Count number of students in each
city.
THEORY - This problem uses a dictionary data structure to store
information about n persons where each key represents a person’s name and
each value represents the city in which they live. The dictionary structure allows
fast access to data using unique keys and supports efficient data organization.
By using built-in dictionary methods, all names can be displayed using .keys(),
all city names using .values(), and both name and city together using .items().
To count the number of students in each city, the program groups entries based
on the city value and maintains a frequency count for each city, demonstrating
the concept of data aggregation. This task highlights how dictionaries can be
effectively used for data storage, retrieval, grouping, and analysis in real-world
data management applications.

CODE - n = int(input("Enter the number of person: "))


person_dict = {} for i in range(n):
name = input(f"Enter name of person {i+1}: ")
city = input(f"Enter city of person {i+1}: ")
person_dict[name] = city print("\nNames of all
persons:") for name in person_dict.keys():
print(name)
print("\nCity names of all persons:") for
city in person_dict.values():
print(city)
print("\nName and city of all persons:") for
name, city in person_dict.items():
print(f"{name} - {city}")
city_count = {} for city in
person_dict.values(): if city
in city_count:
city_count[city] += 1 else:
city_count[city] = 1
print("\nNumber of persons in each city:") for
city, count in city_count.items():
print(f"{city}: {count}")
OUTPUT –

QUESTION 5:- Store details of n movies in a dictionary by taking input


from the user. Each movie must store details like name, year, director name,
production cost, collection made (earning) & perform the following :- a) print
all movie details b) display name of movies released before 2015 c) print
movies that made a profit. d) print movies directed by a particular director.

THERORY - This problem uses a dictionary to store details of n movies,


where each movie is represented as a key-value pair: the movie name acts as the
key, and the value is another nested dictionary containing attributes such as
release year, director name, production cost, and collection (earnings). This
nested dictionary structure allows structured and organized storage of complex
data. By traversing the dictionary using loops and dictionary methods, different
operations can be performed, such as displaying complete movie details,
filtering movies released before a specific year (2015), identifying profitable
movies by comparing collection with production cost, and searching movies by
a particular director’s name. This approach demonstrates how dictionaries
support hierarchical data storage, efficient searching, filtering, grouping, and
real-world data modeling in programming.

CODE - n = int(input("Enter number of movies: ")) movies


= {}

for i in range(n):
name = input("\nMovie name: ") year =
int(input("Release year: ")) director =
input("Director name: ") cost =
float(input("Production cost: ")) collection =
float(input("Collection made: "))

[Link]({ na
me: {
"year": year,
"director": director,
"cost": cost,
"collection": collection
}
})

print("\n All Movie Details") for


m, d in [Link]():
print(m, d)
print("\nMovies released before 2015")
for m, d in [Link](): if
d["year"] < 2015:
print(m)

print("\nMovies that made profit")


for m, d in [Link](): if
d["collection"] > d["cost"]:
print(m)

director = input("\nEnter director name: ")


print("\n Movies by", director) for m, d in
[Link]():
if d["director"].lower() == [Link]():
print(m)
OUTPUT –

QUESTION 6 - Create a contact book where users can store, search,


update, and delete contacts. Use dictionary for storing contacts.

THEORY - A contact book application uses a dictionary data structure to


store contact information in an efficient and organized way, where each contact
name (or unique identifier) acts as the key and the associated details such as
phone number, email, or address act as the value. This structure allows fast data
access, insertion, and modification operations using keys, making searching,
updating, and deleting contacts simple and time-efficient. By implementing
basic operations like storing new contacts, searching for existing ones, updating
contact details, and deleting contacts, the program demonstrates the practical
use of dictionaries in real-world applications. It also highlights core
programming concepts such as user input handling, data validation, conditional
logic, and dynamic data management in building interactive data-driven
systems.

CODE - ontacts = {} while


True:
print("\n--- Contact Book ---")
print("1. Add Contact") print("2.
View Contacts") print("3.
Search Contact") print("4.
Update Contact") print("5.
Delete Contact") print("6. Exit")

choice = input("Enter your choice: ")

if choice == "1":
name = input("Enter contact name: ")
phone = input("Enter contact phone number: ")
contacts[name] = phone
print(f"Contact '{name}' added successfully!")

elif choice == "2":


if not contacts:
print("No contacts in the book.")
else:
print("\nYour Contacts:") for
name, phone in [Link]():
print(f"{name}: {phone}")

elif choice == "3":


name = input("Enter contact name to search: ")
if name in contacts:
print(f"Contact found: {name} - {contacts[name]}")
else:
print("Contact not found.")

elif choice == "4":


name = input("Enter contact name to update: ")
if name in contacts:
new_phone = input(f"Enter new phone number for {name}: ")
contacts[name] = new_phone
print(f"Contact '{name}' updated successfully!")
else:
print("Contact not found.")

elif choice == "5":


name = input("Enter contact name to delete: ")
if name in contacts: del contacts[name]
print(f"Contact '{name}' deleted successfully!")
else:
print("Contact not found.")

elif choice == "6":


print("Exiting Contact Book. Goodbye!")
break

else:
print("Invalid choice. Please try again.")
OUTPUT –

OUESTION 7 - Create a Todo list Manager where users can add, view,
and remove tasks. Use List for storing tasks.
THEORY - A Todo List Manager uses a list data structure to store tasks in
an ordered and dynamic way, allowing users to easily add, view, and remove
tasks. Since lists in Python are mutable, tasks can be inserted, modified, and
deleted efficiently during program execution. The program typically runs in a
loop with a menu-driven interface where users choose operations such as adding
a new task, displaying all tasks, or removing a selected task. Indexing and
iteration over the list are used to manage and display tasks in a structured
manner. This application demonstrates fundamental programming concepts
such as list manipulation, user input handling, looping, conditional logic, and
basic data management, making it a simple yet practical example of using lists
for real-world task organization.

CODE tasks = []

while True:
print("\n--- Todo List Manager -
--") print("1. Add
Task") print("2. View
Tasks") print("3.
Remove Task") print("4.
Exit")

choice = input("Enter your


choice: ")

if choice == "1":
task = input("Enter task: ")
[Link](task)
print(f"Task '{task}' added
successfully!")

elif choice == "2":


if not tasks:
print("No tasks in the
list.") else:
print("\nYour Todo List:")
for i, task in enumerate(tasks,
start=1):
print(f"{i}. {task}")

elif choice == "3":


if not tasks:
print("No tasks to
remove.") else:
print("\nYour Todo List:")
for i, task in enumerate(tasks,
start=1):
print(f"{i}. {task}")
try:
task_number =
int(input("Enter task number to
remove: ")) if 0 <
task_number <= len(tasks):
removed =
[Link](task_number - 1)
print(f"Task
'{removed}' removed
successfully!")
else:
print("Invalid task
number.")
except ValueError:
print("Please enter a
valid number.")
elif choice == "4":
print("Exiting Todo List Manager.
Goodbye!")
break

else:
print("Invalid choice. Please try
again.")

OUTPUT –

You might also like