Python SQLite3项目实现do-while逻辑 添加操作后继续确认功能问询
实现方案
你可以在有效操作(添加居民、查询居民列表)完成后加入确认询问逻辑,同时支持大小写的Y/N输入,输入非法字符时会要求重新输入,修改后的完整代码如下:
import Databaseprofile # 可根据需求保留原有英文提示 MENU_PROMPT = """--- 社区居民记录系统 --- 请选择操作选项: [1] 新增居民档案 [2] 查看所有居民列表 [3] 退出系统 请输入你的选择: """ def menu(): connection = Databaseprofile.connect() Databaseprofile.create_tables(connection) while (user_input := input(MENU_PROMPT)) != "3": if user_input == "1": print("---新增居民档案---") name = input("输入居民全名: ") birth = input("输入出生日期 (年-月-日): ") sex = input("输入性别: ") purok = int(input("输入所在区编号: ")) house = int(input("输入门牌号: ")) number = int(input("输入手机号: ")) Databaseprofile.add_profile(connection, name, birth, sex, purok, house, number) print("---档案添加成功!---") # 继续确认逻辑 while True: confirm = input("您是否要继续?Y/N: ").strip().upper() if confirm in ("Y", "N"): break print("输入无效,请输入Y或N") if confirm == "N": break elif user_input == "2": print("--------------------------------------------------------------------------------------------------") print("---居民列表---") profile = Databaseprofile.get_all_profile(connection) for prof in profile: print(f"{prof[0]}, {prof[1]}, {prof[2]}, {prof[3]}, 区 {prof[4]}, 门牌号 {prof[5]}, 手机号 {prof[6]}") print("--------------------------------------------------------------------------------------------------") # 继续确认逻辑 while True: confirm = input("您是否要继续?Y/N: ").strip().upper() if confirm in ("Y", "N"): break print("输入无效,请输入Y或N") if confirm == "N": break else: print("输入无效,请重新选择。") print("感谢使用本系统。") menu()
逻辑说明
- 仅在添加档案、查询列表两个有效操作完成后才会弹出继续确认,输入无效选项时不会弹出
- 自动将输入的y/n转为大写,兼容大小写输入
- 输入非Y/N的内容时会要求重新输入,避免异常
- 选择N时直接终止循环退出程序,选择Y时回到主菜单重新选择操作
内容的提问来源于stack exchange,提问作者Hydroxy21
相关产品推荐
相关产品推荐

