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

Python输入转换异常求助:转int后仍提示输入非整数

正确实现输入整数的转换与验证

错误根源

你的代码不管变量类型对不对都会输出错误提示,核心问题出在判断逻辑完全错误:
你写的if qty != int是在把变量的数值和Python的int类型本身做比较——一个整数数值和类型对象永远不可能相等,所以这个判断永远为True,自然每次都会打印错误信息。

另外你提到初始代码中type(qty)显示为str,应该是输入了非整数内容导致int()转换失败,但调整空格后的代码确实能把有效整数输入转为int类型,只是判断逻辑没改,所以依然出错。

基础修正版本

把判断条件改成检查变量的类型即可:

qty = int(input('enter current quantity :'))
if type(qty) is not int:
    print('input is not integer')
else:
    print('input is valid integer')

更符合Python风格的写法是用isinstance(支持类型继承场景):

qty = int(input('enter current quantity :'))
if not isinstance(qty, int):
    print('input is not integer')
else:
    print('input is valid integer')

健壮性升级(处理非法输入)

上面的代码如果用户输入非整数(比如abc),会直接抛出ValueError导致程序崩溃。用try-except捕获异常才能实现完整的输入验证:

try:
    qty = int(input('enter current quantity :'))
    print('input is valid integer')
    # 在这里添加后续业务逻辑
except ValueError:
    print('input is not integer')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 16:15:43