如何避免类型错误:'float'对象不可下标



我目前收到错误类型错误:"float"对象不可下标,因为我使用 % 除以浮点数。这是我的代码:

def displayBalance(name,ID):
    with sqlite3.connect("ATM.db") as db:
        cursor = db.cursor()
        cursor.execute("select Balance from Atm where CustomerID=?",(ID,))
        balance = cursor.fetchone()
        newBalance = int(balance[0][0]) % 10
        print(newBalance)

现在,我正在尝试将%除法按钮与我为该用户存储的余额一起使用。该金额显然是实数或浮点数,但是我不知道如何绕过此类型错误。有什么想法吗?

balance = cursor.fetchone()

返回包含请求值的tuple。在您的情况下,您要求 1 个值,因此balance元组包含 1 个唯一值,使用 [0] 访问:

newBalance = int(balance[0]) % 10

否则 Python 会尝试"下标"该值(即按索引访问(,这是无效的。

或者,您可以像这样直接解压缩您的价值:

    (balance,) = cursor.fetchone()

然后:

    newBalance = int(balance) % 10

最新更新