-1

Having an issue with checking if user input is in a dictionary.

Basics of program is there's a shop inventory. The items are stored in a dictionary with corresponding values e.g. {'kettle': 3,.....}

Then I want user to write what they want. So if the user has entered 'kettle' I want to remove the item from the shop inventory and put in user inventory.

The main problem right now is just getting an if statement together. This is what I'm trying:

user_choice = input('What would you like to buy? ')
if user_choice in shop_inventory:
    print('Complete')
else:
    print('Fail')

How can I get the program to print "Complete"?

nalzok
  • 14,965
  • 21
  • 72
  • 139
John H
  • 47
  • 1
  • 7

2 Answers2

-1

You can use pop() to remove the item from the shop_inventory.

shop_inventory =  {'kettle': 3}
user_choice = input('What would you like to buy? ')
if user_choice in shop_inventory:
    shop_inventory.pop(user_choice)
    print(shop_inventory)
    print('Complete')
else:
    print('Fail')
Md. Rezwanul Haque
  • 2,882
  • 7
  • 28
  • 45
-4

Instead of input(), use raw_input:

user_choice = raw_input('What would you like to buy? ')
if user_choice in shop_inventory:
    print('Complete')
else:
    print('Fail')

Explanation: In Python 2, raw_input() returns a string, and input() tries to run the input as a Python expression.

In Python 3 there is only raw_input(). It was renamed in input().

As statet here