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
相关产品推荐
相关产品推荐

