In: Computer Science
USE PYTHON-LIST Q1 - You need to keep track of book titles. Write code using function(s) that will allow the user to do the following. 1. Add book titles to the list. 2. Delete book titles anywhere in the list by value. 3. Delete a book by position. Note: if you wish to display the booklist as a vertical number booklist , that is ok (that is also a hint) 4. Insert book titles anywhere in the list. 5. Clear the list (remove all items from the list) 6. Print the list horizontally using sys.stdout.write() 7. Sort the list 8. The user can add, remove, insert, clear, delete, print books as much as they wish. Note: The person will add or remove books, one book at at a time When a book is add, deleted, inserted or sorted the list should automatically be printed
(HINT: a function will make this easy)
###
PYTHON LIST
Program:
import sys #importing sys library List=[] def add(ele): List.append(ele) #adding elements printlist() #printing list def del_by_val(ele): List.remove(ele) #removing element in a list printlist() #printing list def del_by_pos(pos): List.pop(pos-1) #deleting elemnt by position printlist() #printing list def insert_anywhere(ele,pos): List.insert(pos-1,ele) #inserting element by position printlist() #printing list def clear(): List.clear() #removing all elemnts in a list def printlist(): for i in range(len(List)): sys.stdout.write(List[i]+', ') sys.stdout.write('\n') def sort(): List.sort() #sorting a list printlist() while(1): print('''Press 1. Add book titles to the list. 2. Delete book titles anywhere in the list by value. 3. Delete a book by position. 4. Insert book titles anywhere in the list. 5. Clear the list (remove all items from the list) 6. Print the list horizontally using sys.stdout.write() 7. Sort the list 8.Exit''') k=int(input()) if k==1: ele=input("Enter book title:") add(ele) elif k==2: val=input("enter book title to delete:") del_by_val(val) elif k==3: pos=int(input("Enter position:")) del_by_pos(pos) elif k==4: pos=int(input("enter position:")) ele=input("Enter book title:") insert_anywhere(ele,pos) elif k==5: clear() elif k==6: printlist() elif k==7: sort() else: exit(0)
Program Screenshot:
Output:
Hope you understand...
If you have any doubts comment below...plss dont dislike...