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

Python循环实现汽水选购后询问继续/退出功能求助

问题解决:实现汽水选购循环及退出确认

原代码的问题在于,当前while循环仅在输入不存在的汽水名称时才会终止,完全没实现“选完后询问是否继续”的需求。要实现这个功能,得在每次成功选购后加一步确认逻辑。

修改后的代码如下:

def single_bottles():
    prices = {"Coca Cola": 16, "Pepsi": 14, "Fanta": 16, "7up": 14, 
              "Sprite": 13, "Mt Dew": 16, "Rasberrysoda": 11, "Orangina": 12, 
              "Zingo": 14, "Pearsoda": 14, "Pommac": 16, "Jaffa": 14}

    total = 0

    print('Sodalist\n========')  
    for keys, values in prices.items():    
        print(f'{keys} : {values} kr')    
    
    while True:      
        inp = input('\nWrite name of the soda you want to buy: ').capitalize()      
        try:        
            total += prices[inp]
            # 询问是否继续选购,确保输入有效
            while True:
                continue_choice = input("Do you want to continue buying? (y/n): ").lower()
                if continue_choice in ['y', 'n']:
                    break
                print("Please enter 'y' or 'n'")
            if continue_choice == 'n':
                break
        except KeyError:        
            print("That soda doesn't exist, please try again.")
    print(f'Total price : {total} kr')  

关键改动:

  • 成功选购后新增确认逻辑,循环询问用户是否继续,强制输入有效的y/n
  • 用户选择n时主动退出主循环,结束选购流程
  • 只捕获KeyError(避免捕获所有异常隐藏其他问题),输入错误汽水名称时提示重新输入,而非直接终止程序

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:45:33