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

Python主菜单循环实现问题:如何让菜单重复直至选择退出

Python 主菜单循环逻辑修复

你的代码出现刷屏问题,核心原因是缩进错误——while循环只包含了菜单打印的第一行,后续的菜单内容、输入和判断逻辑都在循环体外,导致循环执行时不断重复打印菜单标题,同时无法正确处理用户输入。另外代码存在大量重复,完全没必要写两遍菜单和判断逻辑。

下面是修正后的代码,实现菜单持续显示直到用户选择退出:

while True:
    # 显示主菜单
    print('''------------
Main Menu
------------''')
    print('1 - show all contacts')
    print('2 - add a new contact')
    print('3 - find contact')
    print('4 - Delete contact')
    print('5 - Quit')

    # 获取用户选择
    choice = input('enter your choice : ')
 
    # 处理用户选择
    if choice == '1':
        print('this is your list : ')
    elif choice == '2':
        print('add your contact : ')
    elif choice == '3':
        print('type in a contact you would like to find')
    elif choice == '4':
        print('type in a contact you would like to delete')
    elif choice == '5':
        print('quitting....')
        break  # 退出循环,结束程序
    else:
        print('无效选项,请输入1-5之间的数字')

关键说明:

  • 用while True创建无限循环,只要用户不选5,就会一直重复显示菜单
  • 把菜单显示、输入获取、选择判断全部放在循环内部,避免代码重复
  • 选择5时用break跳出循环,程序自然结束(比quit()更规范)
  • 新增了无效输入的处理,提示用户输入正确选项

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:35:11