判断用户输入是否在字典的值中(python练习)

部署运行你感兴趣的模型镜像

编写一个程序:判断一个值(由用户输入)是否在一个字典中。

  • 创建my_dict字典,其键和值为{"a": "juice", "b": "grill", "c": "corn"}
  • 用户输入的字符串,存储在变量data中。
  • 创建flag变量,初始化为 False
  • 使用 for 来循环遍历字典 my_dict
  • 在这个循环中,判断用户输入的值是否在字典中。
  • 如果是,将flag设置为True并终止循环。
  • 在循环外,如果flag等于True,则打印"找到值",否则打印"未找到值"

输入格式

一个字符串

示例输入

corn

示例输出

找到值

my_dict = {"a": "juice", "b": "grill", "c": "corn"}

# 用户输入
data=input()

# 创建 flag 变量并将其设置为 False
flag=False

# 循环字典
for element in my_dict:
    # 如果用户输入的值在字典中,将 flag 设置为 True 并终止循环
    if my_dict[element]==data:
        flag=True
        break

# 根据 flag 值打印结果
if flag == True:
    print('找到值')
else:
    print('未找到值')

您可能感兴趣的与本文相关的镜像

Python3.11

Python3.11

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

### Python 中关于元组和字典练习题 以下是几个涉及 Python 元组和字典的经典练习题及其解答: #### 练习题 1:统计字符串中的大小写字母数量 编写一个函数 `fun`,接收一个字符串参数,返回一个元组 `(upper_count, lower_count)`,其中第一个表示大写字母的数量,第二个表示小写字母的数量。 ```python def fun(x): upper_count = 0 lower_count = 0 for item in x: if item.isupper(): upper_count += 1 elif item.islower(): lower_count += 1 else: continue return upper_count, lower_count result = fun('ehllo WROLD') print(result) # 输出应为 (5, 5)[^1] ``` --- #### 练习题 2:创建菜单字典并打印键对 通过用户输入动态创建一个菜单字典 `menu_dict`,其键为食物名称,为其对应的价格。最后分别打印所有的键和。 ```python menu_dict = {} while True: try: food = input("请输入食物名称(单独回车结束):") if not food.strip(): # 如果输入为空,则退出循环 break price = int(input("请输入价格:")) menu_dict[food] = price except ValueError: print("输入有误,请重新输入!") for k in menu_dict.keys(): # 打印所有键 print(f"食物名称: {k}") for v in menu_dict.values(): # 打印所有 print(f"价格: {v}") ``` 此代码片段展示了如何利用异常处理机制来捕获非法输入,并实现动态构建字典的功能[^2]。 --- #### 练习题 3:查找特定模式的元素 给定三个容器(列表、元组、字典),找出以字母 `'a'` 或 `'A'` 开头且以 `'c'` 结尾的所有元素。 ```python li = ["alec", "aric", "Alex", "Tony", "rain"] tu = ("alec", "aric", "Alex", "Tony", "rain") dic = {'k1': "alex", 'k2': 'aric', "k3": "Alex", "k4": "Tony"} list1 = list(tu) list2 = list(dic.values()) newlist = li + list1 + list2 results = [] for i in newlist: stripped_i = i.strip() if (stripped_i.startswith('a') or stripped_i.startswith('A')) and stripped_i.endswith('c'): results.append(stripped_i) print(results) # 输出 ['alec', 'aric', 'alec', 'aric', 'aric'][^3] ``` --- #### 练习题 4:去除重复项的方法比较 提供两种方法用于从列表中去除重复项,一种基于字典去重,另一种基于集合去重。 ##### 方法一:使用字典去重 ```python a_list = [1, 1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 3, 5, 2] a_dic = {key: 0 for key in a_list} ans = list(a_dic.keys()) print(ans) # 输出 [1, 2, 3, 4, 5, 6, 7][^4] ``` ##### 方法二:使用集合去重 ```python a_list = [1, 1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 3, 5, 2] ans = list(set(a_list)) print(ans) # 输出可能顺序不同,如 [1, 2, 3, 4, 5, 6, 7][^4] ``` --- #### 练习题 5:将数分类存储到字典中 将一组整数分为两类,一类存入字典一个键对应的列表中,另一类存入另一个键对应的列表中。 ```python data = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90] dictionary = {} greater_than_66 = [] less_than_66 = [] for value in data: if value > 66: greater_than_66.append(value) elif value < 66: less_than_66.append(value) dictionary['k1'] = greater_than_66 dictionary['k2'] = less_than_66 print(dictionary) # 输出 {'k1': [77, 88, 99, 90], 'k2': [11, 22, 33, 44, 55]}[^5] ``` --- #### 练习题 6:模拟购物程序 设计一个简单的购物车功能,允许用户选择商品加入购物车,并判断总金额是否超出预算。 ```python goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "美女", "price": 998}, ] total_assets = int(input("请输入您的总资产:")) shopping_cart = {} cart_total_price = 0 for idx, product in enumerate(goods, start=1): shopping_cart[idx] = product["name"] print(shopping_cart) while True: choice = int(input("请选择要购买的商品编号(输入0结束选购):")) if choice == 0: break selected_product_name = shopping_cart.get(choice) if selected_product_name is None: print("无效的选择,请重新输入!") continue selected_product_price = next(item["price"] for item in goods if item["name"] == selected_product_name) cart_total_price += selected_product_price print(f"已将{selected_product_name}加入购物车,总价目前为{cart_total_price}") if cart_total_price > total_assets: print("余额不足,无法完成购买!") else: print("购买成功!感谢惠顾!")[^5] ``` --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值