You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中实现重复输入检测及优化购物清单代码?

Python条件语句与购物清单代码优化

一、实现输入重复两次时触发错误提示

根据需求分两种场景实现:

1. 连续两次输入相同内容触发错误

适合需要限制连续重复输入的场景,代码逻辑如下:

prev_input = ""
repeat_times = 0

while True:
    user_input = input("请输入内容:").strip()
    if user_input == prev_input:
        repeat_times += 1
        if repeat_times >= 2:
            print("错误:连续重复输入两次!")
            break
    else:
        repeat_times = 0  # 非重复输入时重置计数
    prev_input = user_input
    print(f"当前输入:{user_input}")

2. 累计输入相同内容两次触发错误

不管输入间隔,只要某内容总共出现两次就触发错误:

input_records = []

while True:
    user_input = input("请输入内容:").strip()
    input_records.append(user_input)
    if input_records.count(user_input) >= 2:
        print("错误:该内容已输入过两次!")
        break
    print(f"当前输入:{user_input}")

二、购物清单代码优化(含重复物品检测)

针对你提供的代码,优化后不仅能检测重复添加,还能适配实际购物场景的多次操作,代码如下:

# 初始化购物篮与推荐水果列表
shopping_basket = []
recommended_fruits = ['Banana', 'Mandarine', 'Apple']

while True:
    # 统一输入大小写,避免大小写导致的误判
    target_fruit = input("\n请输入要购买的水果(输入'quit'退出):").strip().capitalize()
    
    # 处理退出逻辑
    if target_fruit == 'Quit':
        print(f"\n最终购物篮:{shopping_basket}")
        break
    
    # 检测是否已在购物篮中
    if target_fruit in shopping_basket:
        print(f"提示:{target_fruit}已经在购物篮里了,无需重复添加!")
        continue
    
    # 处理推荐水果
    if target_fruit in recommended_fruits:
        shopping_basket.append(target_fruit)
        print(f"已添加【{target_fruit}】到购物篮")
    # 处理非推荐水果的确认逻辑
    else:
        choice = input(f"{target_fruit}不在推荐列表中,是否添加?(y/n):").strip().lower()
        if choice == 'y':
            shopping_basket.append(target_fruit)
            print(f"已添加【{target_fruit}】到购物篮")
        else:
            print(f"未添加【{target_fruit}】")

主要优化点:

  • 用循环实现多次输入操作,符合购物清单的实际使用场景
  • 统一输入字符串的大小写,避免banana和Banana被判定为不同物品
  • 增加重复添加检测逻辑,直接判断目标水果是否已在购物篮中
  • 新增非推荐水果的确认机制,提升交互合理性
  • 拆分功能模块,代码逻辑更清晰易维护

内容的提问来源于stack exchange,提问作者Jackson Nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 03:44:57