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

标签 python

我该如何实现这一点,因为当我运行代码时,如果我输入金额和我想要的 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/

相关文章:

Python:装饰器:以下代码如何工作?

python - 向列表中的对象添加属性,python

python - 使用 dateutil.parser.parse 抛出两位数年份日期的 ValueError

python - pandas 数据框不会根据条件进行更新

python - 关于 tkinter 按钮的基本问题

python - DJANGO_SETTINGS_MODULE 未定义

python - 类定义中的属性分配顺序

python - 将函数名称作为参数传递以定义通用函数

python - 如何在前一个字符串Python的末尾打印字符串

python - 如何使用 max() 函数找到字典中最大值对应的键?