找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 1970|回复: 4

[求助] Python萌新求助怎么将input输入的内容限制在字典的键值之中?

0

主题

1

帖子

1

积分

贫民

积分
1
旺仔牛奶唐 发表于 2022-12-31 21:52:33 | 显示全部楼层 |阅读模式
本帖最后由 旺仔牛奶唐 于 2022-12-31 21:57 编辑

怎么将input输入的内容限制在字典的键值之中?
def carculate(money,price):
    result = int(money)-int(price)
    if int(result)>0:
        print(f"Send back you {int(result)}")
    elif int(result)==0:
        print(f"Thankyou for shopping!")
    elif int(result)<0:
        left_money=0-int(result)
        print(f"Sorry,you need {left_money} more to pay!")
active = True
while active:
    prices={"cake1":12,'cake2':24,'cola1':56,'cola2':78,'candy1':34,'candy2':57}
    price=prices[input(f"Chose your goods:\n").lower()]
    money=input("Give the money:\n")
    carculate(money,price)
    asking=input(f"Have you finihed? anser'yes'or'not'.\n")
    if asking.lower() == 'yes':
        print(f"See you next time!")
        break
    else:
        print(f"All depends on you.")
        continue
在 price=prices[input(f"Chose your goods:\n").lower()]一行,成功把输入内容限制在字典prices的键之内,但是输入字典没有的内容会直接报错报错,如何更改使得如果用户输入不属于字典键的内容时进行提示而不是直接报错?



回复

使用道具 举报

0

主题

1

帖子

1

积分

贫民

积分
1
旺仔牛奶唐  楼主| 发表于 2022-12-31 21:55:46 | 显示全部楼层
顶顶顶,求看论坛大佬们的实力
回复 支持 反对

使用道具 举报

0

主题

5

帖子

5

积分

贫民

积分
5
wwwxr 发表于 2023-3-10 13:43:03 | 显示全部楼层
不用[]改成.get(),判断一下,为空则print提示
回复 支持 反对

使用道具 举报

0

主题

956

帖子

956

积分

圣骑士

积分
956
sheeboard 发表于 2023-3-29 09:56:21 | 显示全部楼层
cake=input(f"Chose your goods:\n").lower()
if cake not in prices.keys:
    print('Choice again')
    pass
else:
    price=prices[cake]
    ..............
回复 支持 反对

使用道具 举报

0

主题

1

帖子

1

积分

贫民

积分
1
破碎的梦 发表于 2023-4-2 00:10:21 | 显示全部楼层
def calculate(money, price):
    result = int(money) - int(price)
    if int(result) > 0:
        print(f"Send back you {int(result)}")
    elif int(result) == 0:
        print(f"Thank you for shopping!")
    elif int(result) < 0:
        left_money = 0 - int(result)
        print(f"Sorry, you need {left_money} more to pay!")


active = True
prices = {"cake1": 12, "cake2": 24, "cola1": 56, "cola2": 78, "candy1": 34, "candy2": 57}

while active:
    chosen_item = ""
    while chosen_item not in prices:  # 输入内容限制在prices的键之内
        chosen_item = input("Choose your goods:\n").lower()
        if chosen_item not in prices:
            print("Invalid item. Please choose again.")
    price = prices[chosen_item]
    money = input("Give the money:\n")
    calculate(money, price)
    asking = input("Have you finished? Answer 'yes' or 'no'.\n")
    if asking.lower() == "yes":
        print("See you next time!")
        break
    else:
        print("All depends on you.")
        continue
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表