Home > Software engineering >  shopping list adds "quit" letter to list instead of breaking while loop and exiting progra
shopping list adds "quit" letter to list instead of breaking while loop and exiting progra

Time:09-22

I have been trying to get this quit function to work, if I enter a lowercase "q", it works no problem. But when I enter capital "Q" it gets added to the list instead of breaking the loop. I dont understand why it doesn't work. Any help is appreciated.

shopping_list = []
quit_list = 'q'
print("Shopping list")
print("When done, press 'q'")

while True:
item = input("Enter item:")  # User input item
if item == quit_list.casefold():
    break

if item in shopping_list:  # Remove item by typing same item.
    shopping_list.remove(item)
    print(shopping_list)
else:
    shopping_list.append(item)  # Add item to list
    print("{} added to list.".format(item))
    print(shopping_list)

print(shopping_list)

CodePudding user response:

shopping_list = []
quit_list = 'q'
print("Shopping list")
print("When done, press 'q'")

while True:
    item = input("Enter item:")  # User input item
    if item.casefold() == quit_list:
        break

    if item in shopping_list:  # Remove item by typing same item.
        shopping_list.remove(item)
        print(shopping_list)
    else:
        shopping_list.append(item)  # Add item to list
        print("{} added to list.".format(item))
        print(shopping_list)
print(shopping_list)

You want to make item lowercase, not quit_list.

CodePudding user response:

or use an explicit list of quit options:

shopping_list = []
quit_list = ['q','Q']
print("Shopping list")
print("When done, press 'q' or 'Q'")

while True:
    item = input("Enter item:")  # User input item
    if item in quit_list:
        break
    
    if item in shopping_list:  # Remove item by typing same item.
        shopping_list.remove(item)
        print(shopping_list)
    else:
        shopping_list.append(item)  # Add item to list
        print("{} added to list.".format(item))
        print(shopping_list)

CodePudding user response:

You have a problem with indentation and the logic is mixed up: if quit_list == item.casefold():

shopping_list = []
quit_list = 'q'
print("Shopping list")
print("When done, press 'q'")

while True:
    item = input("Enter item:")  # User input item
    if quit_list == item.casefold():
        break

    if item in shopping_list:  # Remove item by typing same item.
        shopping_list.remove(item)
        print(shopping_list)
    else:
        shopping_list.append(item)  # Add item to list
        print("{} added to list.".format(item))
        print(shopping_list)

CodePudding user response:

try this:

import keyboard

while True:
    item = input("Enter item:")  # User input item
    if keyboard.is_pressed("q"):
        break

you need to install keyboard:

pip install keyboard
  • Related