Python 3.x 如何避免类型错误:';浮动';对象不可下标
我当前收到错误TypeError:“float”对象不可下标,因为我使用%除以一个浮点数。这是我的代码:Python 3.x 如何避免类型错误:';浮动';对象不可下标,python-3.x,sqlite,Python 3.x,Sqlite,我当前收到错误TypeError:“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 = curs
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)
现在,我正在尝试使用我为该用户存储的余额的%divide按钮。金额显然是实数或浮点数,但我不知道如何绕过这个类型错误。有什么想法吗
balance = cursor.fetchone()
返回带有请求值的元组。在您的情况下,您要求的是1个值,因此balance
是一个包含1个唯一值的元组,使用[0]
访问:
newBalance = int(balance[0]) % 10
否则python会尝试“下标”该值(即通过索引访问),这是无效的
或者,您可以像下面这样直接解压缩您的值:
(balance,) = cursor.fetchone()
然后:
int(余额[0][0])%10
=>int(余额[0])%10这是显而易见的。谢谢你,简。
newBalance = int(balance) % 10