首页 > 解决方案 > Python 3.6 - “NoneType”测试失败

问题描述

我正在从sqlite3数据库中读取并过滤掉NoneType,因为我只想要不是的 None。我尝试了这里建议的两种方法,结果相同。这让我认为下面的 if 语句是正确的,但我错过了一些更基本的东西。任何建议表示赞赏。

从数据库中读取

        conn.commit()
        c.execute("SELECT tact FROM LineOEE03 ORDER BY tact DESC LIMIT 1")
        current_tact = c.fetchone()

无类型测试

        if current_tact is not None:
            current_tact = int(current_tact[0])
        else:
            current_tact = 60

错误

current_tact = int(current_tact[0])

TypeError: int() 参数必须是字符串、类似字节的对象或数字,而不是“NoneType”

标签: pythonpython-3.x

解决方案


您可以添加一个额外的测试来检查列表中的第一项是否不是None,这是您实际尝试转换为整数的内容:

if current_tact is not None and current_tact[0] is not None:
    current_tact = int(current_tact[0])

或使用try-except块来避免完全测试:

try:
    current_tact = int(current_tact[0])
except TypeError:
    current_tact = 60

推荐阅读