gpt4 book ai didi

python - 我如何使其他输入工作,它只显示第一选择的结果

转载 作者:行者123 更新时间:2023-12-04 08:24:05 26 4
gpt4 key购买 nike

我如何使其工作,因为当我运行代码时,如果我输入金额和我想要的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com