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

Python中type()函数为何无法在if语句中正常工作?

代码无输出的问题分析与解决

你的代码如下:

user_input = int(input('Enter input: '))

if type(user_input) == "<class 'int'>":
    print('This is a integer.')

问题根源

你错误地把type()返回的类型对象和字符串字面量做了比较。type(user_input)返回的是int这个类型本身(<class 'int'>只是它的字符串打印形式,对象本身并不是字符串),用==去对比字符串"<class 'int'>",两者永远不可能相等,所以if条件永远不成立,自然不会执行print语句。

正确写法

有两种可靠的类型判断方式:

  1. 直接对比类型对象:
user_input = int(input('Enter input: '))

if type(user_input) == int:
    print('This is an integer.')
  1. 更推荐的isinstance写法(支持继承场景,比如判断子类实例):
user_input = int(input('Enter input: '))

if isinstance(user_input, int):
    print('This is an integer.')

补充说明

你移除int()转换后依然无输出,原因和上面一致:此时user_input是str类型对象,和字符串"<class 'int'>"对比还是不相等,所以print不会执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 17:20:59