This article demonstrates how to create a simple menu-driven program in Python to perform CRUD operations on a list.
It helps beginners understand functions, conditionals, loops, and basic data handling through a practical example.
Code
data = []
# def insert(list1, value):
# list1.append(value)
# return "Value added successfully!"
def insert(data):
user_input = input("Enter values (space or comma separated): ")
items = user_input.replace(",", " ").split()
for item in items:
data.append(int(item))
return "Values added successfully!"
def display(list1):
return "No records" if not list1 else list1
def update(list1, old_value, new_value):
if old_value in list1:
index = list1.index(old_value)
list1[index] = new_value
return "Item updated successfully"
return "Item not found"
def searching(list1, value):
if value in list1:
return list1.index(value) + 1
return -1
def delete_item(list1, value):
if value in list1:
list1.remove(value)
return "Item deleted successfully"
return "Item not found"
def sort_list(list1):
list1.sort()
return list1
def reverse_list(list1):
list1.reverse()
return list1
while True:
print("\n----- Management System -----")
print("1. Add Value")
print("2. Display Values")
print("3. Update Value")
print("4. Search Value")
print("5. Delete Value")
print("6. Sort List")
print("7. Reverse List")
print("0. Exit")
choice = int(input("Enter your choice: "))
match choice:
case 1:
# val = int(input("Enter value: "))
print(insert(data))
case 2:
print(display(data))
case 3:
old = int(input("Enter old value: "))
new = int(input("Enter new value: "))
print(update(data, old, new))
case 4:
val = int(input("Enter value to search: "))
pos = searching(data, val)
print(f"Found at position {pos}" if pos != -1 else "Item not found")
case 5:
val = int(input("Enter value to delete: "))
print(delete_item(data, val))
case 6:
print("Sorted List:", sort_list(data))
case 7:
print("Reversed List:", reverse_list(data))
case 0:
print("You are exited")
break
case _:
print("Wrong choice")
Top comments (0)