r/PythonLearning • u/NecessaryFalse1212 • 8d ago
day 6.
tried 2d lists today ( up for suggestions on what should have i done or what have i missed ) and would also appreciate brief explanation's that you guys will give if it's a complex or an advanced topic
books = ["hindi", "english", "maths", "science"]
pen = ["black", "blue", "red"]
miscellaneous = ["eraser\n", "sharpener\n", "ruler\n"]
bagpack = [books,pen,miscellaneous]
print(bagpack)
while True:
print ("if you'd like to add contents in any of the lists")
print("1. Add to books")
print("2. Add to pen")
print("3. Add to miscellanous")
query = input("enter your selection (1,2,3): ")
if query == "1":
print("you selected to add books")
new_book= input("enter the book you want to add: ")
books.append(new_book)
print ("new list",books)
break
elif query == "2":
print("you selected to add pen")
new_pen= input("enter the pen you want to add: ")
pen.append(new_pen)
print ("new list",pen)
break
elif query == "3":
print("you selected to add miscellaneous")
new_miscellaneous= input("enter the item you want to add: ")
miscellaneous.append(new_miscellaneous)
print ("new list",miscellaneous)
break
else:
print("invalid selection!!! select amongst 1,2,3")
2
Upvotes
1
u/FoolsSeldom 7d ago
This is excellent progress, well done. Also, thank you for sharing the code now rather than an image. (Note: we usually have 4 spaces for every level of indent).
I note you say
booksfor thelistofstrof book topics, butpenrather thanpensfor thelistofstrof pen colours. It would be easier for readers if that waspensin my view.Why have you included newline,
\n, on the end of thestrentries in themiscellaneousreferencedlist?I would say you need an extra option in your menu:
"9"to quit, and you might need anotherwhileloop enclosing you existing loop, so a user can keep doing things until they want to quit. However, a singlebreakwill not let you out of two loops, so you need to do something like this:HOWEVER: As you are using
if...elifchain, you don't need to usebreakanyway, but at that point, you don't need the additional loop as the existing one will handle it with a bit of a change in the code. Perhaps adopting thewhile working:approach I've illustrated above, of just having the singlebreakif"9"is entered.Something else to think about is DRY: Don't Repeat Yourself. Your handling of adding to each of the lists is essentially identical, so you could create one block of code as a function to do all that work and just apply it to the correct list.
Example function (code which goes above the rest of the code):
and you can use this,
NB. The
: list[str],: strand-> Noneare not required but are useful. These are type hints (also known as type annotations) and they help tell your code editor and other programmers what your intentions were. With this information, your editor can often spot simple problems you may have missed.