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

如何检查用户输入是否为整数?Python菜单选择功能异常排查

问题分析

你的代码核心问题是类型不匹配:

  • input()获取的用户输入是字符串类型,你在try块里把它转成了整数,但没有把转换后的结果赋值回choice变量,所以choice依然是字符串。
  • 而match语句里的case是整数(case 1、case 2),字符串和整数永远无法匹配,所以所有输入都会走到case _分支,触发"无效选择"提示。
修复代码
def update_profile():
    while True:
        print("Choose the options below to update the info")
        print("1.Username\n2.Password\n3.Email\n4.Date of Birth\n5.Address\n6.Contact Number\n7.Exit")
        choice_input = input("Enter your choice:")

        try:
            # 将输入转换为整数并赋值给choice
            choice = int(choice_input)
        except ValueError:
            # 处理非数字输入的情况
            print("Invalid choice. Please select again.")
            print("--------------------------------------------")
            continue

        match choice:
            case 1:
                print("Updating Username...")
                # 这里编写你的用户名更新逻辑
            case 2:
                print("Updating Password...")
                # 这里编写你的密码更新逻辑
            case 3:
                print("Updating Email...")
                # 这里编写你的邮箱更新逻辑
            case 4:
                print("Updating Date of Birth...")
                # 这里编写你的出生日期更新逻辑
            case 5:
                print("Updating Address...")
                # 这里编写你的地址更新逻辑
            case 6:
                print("Updating Contact Number...")
                # 这里编写你的联系方式更新逻辑
            case 7:
                # 选择7直接退出循环
                print("Exiting profile update...")
                break
            case _:
                print("Invalid choice. Please select again.")
                print("--------------------------------------------")
                continue
        
        # 只有选择1-6时才询问是否继续更新
        repeat = input("Do you want to continue update the profile? <Yes [Y]\tNo [N]>\nYour choice: ")
        if repeat.lower() == 'n':
            break  
关键修改点
  • 将输入存到临时变量choice_input,转换为整数后赋值给choice,确保match时类型一致。
  • 在except块直接处理非数字输入,提前进入下一轮循环。
  • 新增case 7的处理逻辑,选择7直接退出,符合菜单设计。
  • 优化repeat的判断,用lower()简化大小写判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 18:05:07