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

Python整数输入校验:输入为字符串时如何输出提示?

解决方案:正确实现整数输入校验

原代码的问题

  1. 直接用int(input(...))转换输入,若输入非数字字符串会直接触发ValueError导致程序崩溃,无法执行后续判断逻辑。
  2. elif age != int逻辑完全错误:age是整数实例,int是类型对象,两者永远不可能相等,该判断没有任何实际作用。

方法一:使用异常捕获(推荐,覆盖更多合法场景)

这种方法能处理所有合法整数输入(包括负数),是Python中处理输入类型校验的标准方式:

while True:
    user_input = input("*--How old are you?: ")
    try:
        # 尝试将输入转换为整数
        age = int(user_input)
        # 年龄判断逻辑
        if age < 18:
            print("Better go home!")
        else:
            print("You're old enough!")
    except ValueError:
        # 转换失败时执行,即输入非合法整数
        print("Use some numbers dude")

方法二:使用isdigit()方法(针对你提到的工具)

isdigit()用于判断字符串是否全部由数字字符组成,适合仅需正整数输入的场景,但无法识别负数、带小数点的数字:

while True:
    user_input = input("*--How old are you?: ")
    if user_input.isdigit():
        age = int(user_input)
        if age < 18:
            print("Better go home!")
        else:
            print("You're old enough!")
    else:
        print("Use some numbers dude")

如果需要支持负数年龄输入,优先选择方法一的异常捕获方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 08:02:47