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

Python解释器跳过else块 传入整数参数时抛出TypeError报错

问题产生原因

bug的根源是if条件的逻辑写法错误:
你写的判断语句type(argument) == tuple or list or dict or set,在Python的运算规则中不会自动将type(argument) ==的比较关系复用在or连接的所有类型上,实际会被解析为4个独立表达式做或运算:

  • 表达式1:type(argument) == tuple
  • 表达式2:list
  • 表达式3:dict
  • 表达式4:set

Python中所有非空的内置类型对象本身的布尔值为True,也就是说后面3个表达式的结果永远为真,导致整个if条件永远成立,无论传入什么参数都不会执行else分支。传入整数时,代码直接尝试遍历整数对象,自然触发'int' object is not iterable报错。
另外原代码用type() ==做类型校验还存在兼容问题:如果传入tuple、list等类型的子类实例,会出现类型判断失效的情况。

修复方案

使用isinstance()做类型检查,将需要匹配的类型统一放在元组中作为参数传入,修正后的完整代码如下:

import numpy

def sqrtt(argument):
    if isinstance(argument, (tuple, list, dict, set)):
        # 注意:直接遍历dict时拿到的是字典的键,如果需要计算字典值的平方根,请改为遍历argument.values()
        result = [int(numpy.sqrt(i)) for i in argument]
    else:
        result = int(numpy.sqrt(argument))
    return result

如果需要兼容更多可迭代对象(比如生成器、自定义可迭代类型),可以额外增加可迭代协议判断,注意要排除字符串类型,避免传入字符串时被逐个字符遍历:

import numpy
from collections.abc import Iterable

def sqrtt(argument):
    if isinstance(argument, Iterable) and not isinstance(argument, str):
        result = [int(numpy.sqrt(i)) for i in argument]
    else:
        result = int(numpy.sqrt(argument))
    return result

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 03:48:22