Home > Back-end >  Python Dict 2 argument, how to exit the while loop with one <enter>
Python Dict 2 argument, how to exit the while loop with one <enter>

Time:03-07

Have written below program, but how to avoid the system checking the two argument when enter is pressed, we are using the enter key to exit the while loop.

while True: # need to exit the while loop thru one <Enter>
    

    itemcode, quantity = input("Enter item code and quantity (Press <Enter> key to end): ") .split()


    if itemcode == " " : #got two argument, one enter will crash the system, how to amend it
        return
    
    if itemcode not in orderdict.keys():
        print("Invalid item code! Try again.")
        continue

    if itemcode in orderdict.keys():
        orderdict [itemcode] = orderdict 
        #print("{:4s} {:<3d} {:<3d} X {:<3d} ".format(itemcode, [0], [1], [3]))    
    
    else :
        input ()   
        break

CodePudding user response:

Your problem is that the first line is hardcoded in such a way that the program expects two, and exactly two, values separated by a space. If you give it less than two (and simply hitting "enter" means giving it zero values), or more than two, this causes a traceback because the expected number of values isn't there.

If you don'T trust your users to enter the correct number of values, then I think you can avoid a crash either with a try/exception block, or a simple loop that repeats promtping the user for input until the number of entered values is exactly two:

while True:
    entry_list = input("Enter item code and quantity (Press <Enter> key to end): ") .split()
    if len(entry_list) == 2:
        itemcode = entry_list[0]
        quantity = entry_list[1]
        break

CodePudding user response:

You can start to ask the user to enter only the value of the item and check this value if it is an enter key, then break the loop. Otherwise, check the value of the item if it is within the keys if so, then ask the user for the corresponding quantity. I think you need to replace orderdict with the corresponding quantity for the item entered by the user.

orderdict = {"car":50,"plane":60,"bus":100} # example

while True: 

    itemcode = input("Enter item code and quantity (Press <Enter> key to end): ")

    if itemcode == "" :
        break
    elif itemcode not in orderdict:
        print("Invalid item code! Try again.")
    else:
        orderdict [itemcode] = input("Enter the quantity: ") 

Note: you do not need to write orderdict.keys(), you can use only the name of a dictionary to iterate through the keys of orderdict.

  • Related