Python Forum
Convert SQLite Fetchone() Result to float for Math
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert SQLite Fetchone() Result to float for Math
#1
Hello,

I have an SQLite Statement that fetches one result.
Output:
(1.5,)
The problem is when I try using that result for math:
                        MaterialUsedPrice = SelectedItemQuantity * SellPrice
                        print('Price: $',MaterialUsedPrice)
I get this:
Error:
MaterialUsedPrice = SelectedItemQuantity * SellPrice TypeError: can't multiply sequence by non-int of type 'tuple'
Is there a way to convert the tuple result to a float or something so I can use it in my Multiplication statement?

Thanks in advance?

Code Snippet:
                        #Connect to the inventory database (inventory.db)
                        connection = sqlite3.connect(InventoryDatabase)
                        cursor = connection.cursor()
                        cursor.execute("SELECT Sell_Price_$ FROM items WHERE Name = ?",(SelectedItemName,))
                        connection.commit()
                        SellPrice = cursor.fetchone()
                        
                        # #Update the quantity
                        # cursor.execute("UPDATE items SET Quantity = Quantity - ? WHERE Name = ?",(SelectedItemQuantity, SelectedItemName,))
                        # connection.commit()
                        
                        #Close the connection
                        connection.close()

                        MaterialUsedPrice = SelectedItemQuantity * SellPrice
                        print('Price: $',MaterialUsedPrice)
Reply
#2
What is a tuple? If you really think about what a tuple is, the answer to your question should be obvious.
ndc85430 likes this post
Reply
#3
One way, would be to unpack the tuple...

fpn = tuple[0]
... where fpn is a variable to hold the floating point number and tuple is the tuple to be unpacked.
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#4
(Aug-01-2022, 08:31 PM)rob101 Wrote: One way, would be to unpack the tuple...

fpn = tuple[0]
... where fpn is a variable to hold the floating point number and tuple is the tuple to be unpacked.

I tried that already.
                        x = SellPrice[0]
                        print(x)

                        #Calculate the Price of Material Used
                        MaterialUsedPrice = SelectedItemQuantity * x
                        print(SelectedItemName, ' Used Price: $',MaterialUsedPrice)
This is what I got (Which is right and that's what I want, but it won't let me do anything with it):
Output:
1.5
Followed By:
Error:
MaterialUsedPrice = SelectedItemQuantity * x TypeError: can't multiply sequence by non-int of type 'float'
Reply
#5
Are you sure that TypeError is not coming from SelectedItemQuantity?
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#6
(Aug-01-2022, 08:47 PM)rob101 Wrote: Are you sure that TypeError is not coming from SelectedItemQuantity?

Ya I'm sure.

Even if I do this:
                        x = SellPrice[0]

                        #Calculate the Price of Material Used
                        MaterialUsedPrice = 2 * x
                        print(SelectedItemName, ' Used Price: $',MaterialUsedPrice)
I get:
Error:
x = SellPrice[0] TypeError: 'NoneType' object is not subscriptable
Reply
#7
Humm... okay, but that's not what I see from your last post...

(Aug-01-2022, 08:40 PM)Extra Wrote: x = SellPrice[0]
print(x) 

(Aug-01-2022, 08:40 PM)Extra Wrote: Output:1.5

So, have you tried a debug print?

print(type(SellPrice))
x = SellPrice[0]
print(type(x))
print(type(SelectedItemQuantity))
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#8
You have a lot of errors.

This error indicates that SelectedItemQuantity is a sequence, not a number.
Error:
x = SellPrice[0] MaterialUsedPrice = SelectedItemQuantity * x TypeError: can't multiply sequence by non-int of type 'float'
I get the same error when I run this:
SelectedItemQuantity  = [1, 2, 3]
SellPrice = (1.23,)
print(SelectedItemQuantity   * SellPrice [0])
The error is caused by SelectedItemQuantity , not SellPrice.

This error is probably caused by a failed query.
Error:
x = SellPrice[0] TypeError: 'NoneType' object is not subscriptable
I get the same error if I do this:
SellPrice = None
x = SellPrice[0]
Do you test if fetchone() returns None? According to the documentation:
Quote:fetchone()
Fetch the next row of a query result set as a tuple. Return None if no more data is available.
None is an expected return value. You might get None because there was no matches to your query, or you might get None because you already fetched all the results. Your program needs to check for these conditions.
Reply
#9
(Aug-01-2022, 09:07 PM)rob101 Wrote: Humm... okay, but that's not what I see from your last post...

(Aug-01-2022, 08:40 PM)Extra Wrote: x = SellPrice[0]
print(x) 

(Aug-01-2022, 08:40 PM)Extra Wrote: Output:1.5

So, have you tried a debug print?

print(type(SellPrice))
x = SellPrice[0]
print(type(x))
print(type(SelectedItemQuantity))

I get:
Output:
<class 'tuple'> <class 'float'> <class 'str'>
So my SelectedItemQuantity is of type String which cannot be multiplied to a float (x = SellPrice[0]) but even if I try to do 2*x for testing
I get: x = SellPrice[0] TypeError: 'NoneType' object is not subscriptable

Which confuses me because an int and a float should be able to be multiplied together.


Full Code Snippet:
    def SubmitClicked(self):

        #Get User Inputted Quantity & Material
        for widget in self.MaterialUsedFrame.children():        
            if isinstance(widget, QSpinBox):
                    SelectedItemQuantity = widget.text()
            if isinstance(widget,QComboBox):
                    SelectedItemName = widget.currentText()
                    print(SelectedItemQuantity, ',' ,SelectedItemName)
        
                    #Connect to the inventory database (inventory.db)
                    connection = sqlite3.connect(InventoryDatabase)
                    cursor = connection.cursor()
                    cursor.execute("SELECT Main_Category FROM items WHERE Name = ?",(SelectedItemName,))
                    connection.commit()
                    Result = cursor.fetchone()
                    #Close the connection
                    connection.close()
                    print(Result)

                    if Result == ('Wire',):
                        #Connect to the inventory database (inventory.db)
                        connection = sqlite3.connect(InventoryDatabase)
                        cursor = connection.cursor()
                        cursor.execute("SELECT Price_Per_Ft FROM items WHERE Name = ?",(SelectedItemName,))
                        connection.commit()
                        PricePerFt = cursor.fetchone()
                        #Close the connection
                        connection.close()
                        print(PricePerFt)
                        
                        #Might be better off making all those SpinBoxes Labels
                        #& Just setting the text to the price
                        for widget in self.MaterialPriceFrame.children():        
                            if isinstance(widget, QDoubleSpinBox):
                                widget.setValue(80.80)

                    else: 
                        #Connect to the inventory database (inventory.db)
                        connection = sqlite3.connect(InventoryDatabase)
                        cursor = connection.cursor()
                        cursor.execute("SELECT Sell_Price_$ FROM items WHERE Name = ?",(SelectedItemName,))
                        connection.commit()
                        SellPrice = cursor.fetchone()
                        
                        # #Update the quantity
                        # cursor.execute("UPDATE items SET Quantity = Quantity - ? WHERE Name = ?",(SelectedItemQuantity, SelectedItemName,))
                        # connection.commit()
                        
                        #Close the connection
                        connection.close()

                        print('Selcted Item Quantity: ', SelectedItemQuantity)

                        print(type(SellPrice))
                        x = SellPrice[0]
                        print(type(x))
                        print(type(SelectedItemQuantity))

                        #Calculate the Price of Material Used
                        MaterialUsedPrice = SelectedItemQuantity * SellPrice
                        print('Total ', SelectedItemName, ' Used Price: $', MaterialUsedPrice)
#----------------------------------------------------------------------------------------------------
Reply
#10
So SelectedItemQuantity is a str. You can't do this either:
x = "1"
y = (1.23,)
print(x * y[0])
Error:
print(x * y[0]) TypeError: can't multiply sequence by non-int of type 'float'
You are lucky that your SellPrice is a float. If it was an int Python would happily make bizarre results without any error message ('1' * 2 == '11')
rob101 likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python calculate float plus float is incorrect? sirocawa 6 309 Apr-16-2024, 01:45 PM
Last Post: DeaD_EyE
  convert result to hex ascii Jusufs 6 1,562 May-19-2023, 03:21 PM
Last Post: deanhystad
  math formula does not give the same result as bash script [SOLVED] AlphaInc 3 981 Apr-02-2023, 07:21 PM
Last Post: AlphaInc
  convert string to float in list jacklee26 6 1,929 Feb-13-2023, 01:14 AM
Last Post: jacklee26
  openpyxl convert data to float jacklee26 13 6,033 Nov-19-2022, 11:59 AM
Last Post: deanhystad
  Convert string to float problem vasik006 8 3,425 Jun-03-2022, 06:41 PM
Last Post: deanhystad
  math.log versus math.log10 stevendaprano 10 2,425 May-23-2022, 08:59 PM
Last Post: jefsummers
  Why getting ValueError : Math domain error in trig. function, math.asin() ? jahuja73 3 3,781 Feb-24-2021, 05:09 PM
Last Post: bowlofred
  SQL and fetchone Scorpio 6 6,558 Oct-14-2020, 02:24 PM
Last Post: beebert69
  ValueError: could not convert string to float: RandomCoder 3 5,776 Jul-27-2020, 07:38 AM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020