How do I make the other inputs work, it only displays the result for the first choice

Viewed 23

How do I make this work because when I run the code, if I input the amount of money and the cookie that I want, it just displays the result for the chocolate chip one.

money = int(input('How much money did you recieve? '))
cookie = input('What cookie did he/she want? ')
inventory = {
    'chocolatechip' : 50,
    'oatmeal' : 60,
    'butternut' : 65
}
if cookie in inventory:
    change = money - inventory['chocolatechip']
    if change < 0:
        print('Insufficient Cash')
        print('Please Try Again')
    else:
        print(f'Change: {change}')
        print("Thank you for buying Mark's Chocolate Chip Cookies")
        print('Please Come Again')
elif cookie in inventory:
    change = money - inventory['oatmeal']
    if change < 0:
        print('Insufficient Cash')
        print('Please Try Again')
    else:
        print(f'Change: {change}')
        print("Thank You for buying Mark's Oatmeal Cookies")
elif cookie in inventory:
    change = money - inventory['butternut']
    if change < 0:
        print('Insufficient Cash')
        print('Please Try Again')
    else:
        print(f'Change: {change}')
        print("Thank You for buying Mark's Butternut Cookies")
1 Answers

You might misunderstand the meaning of the construct if key in dict.

With this you can check if the key is in the dictionary, so you can check if the user inputs a valid Cookie name.

Then when you are sure that the cookie exists you just use the cookie variable to get the price and the description from the dictionaries.

Below I provided an example code:

money = int(input('How much money did you recieve? '))
cookie = input('What cookie did he/she want? ')
inventory = {
    'chocolatechip' : 50,
    'oatmeal' : 60,
    'butternut' : 65
}
descr = {
    'chocolatechip' : "Chocolate Chip Cookies",
    'oatmeal' : "Oatmeal Cookies",
    'butternut' : "Butternut Cookies"
}

if cookie in inventory:
    change = money - inventory[cookie]
    if change < 0:
        print('Insufficient Cash')
        print('Please Try Again')
    else:
        print(f'Change: {change}')
        print(f"Thank you for buying Mark's {descr[cookie]}")
        print('Please Come Again')
else:
    print("No Cookies with this name")
Related