我该如何实现这一点,因为当我运行代码时,如果我输入金额和我想要的 cookies ,它只会显示巧克力片的结果。
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")
最佳答案
您可能会误解构造if key in dict
的含义。
通过这个,您可以检查该键是否在字典中,这样您就可以检查用户是否输入了有效的 Cookie 名称。
然后,当您确定 cookie 存在时,您只需使用 cookie
变量即可从字典中获取价格和描述。
下面我提供了示例代码:
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")
关于python - 如何使其他输入起作用,它只显示第一个选择的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65358120/