0
db_quote_cursor.execute("""select lastince 
                           from `here` 
                           order by `date` desc, `time` desc 
                           limit 1""")
thisout= db_quote_cursor.fetchone()

thisout is a single value that is a float. I need to do calculations on it but can't cast it as a float in the tuple.

!work(pleasework=float(thisout[0]))

I tried converting it to a list, that didn't work either. How do I directly access the value within the tuple when I don't want/need to loop through it? Or something else maybe...

Here's what I get back from the database:

print(this out)
# -> ((Decimal('118'),),) 

And this is the error I'm getting:

>>> result = float(thisout[0]) 
Traceback (most recent call last): File "file.1.py", line 56, in <module> 
TypeError: float() argument must be a string or a number 
3
  • 1
    Please post the exact error message you're getting. Thank you. Commented Mar 20, 2012 at 17:52
  • ((Decimal('118'),),) (This is "print(this out)") Traceback (most recent call last): File "file.1.py", line 56, in <module> result=float(thisout[0]) TypeError: float() argument must be a string or a number Commented Mar 20, 2012 at 19:26
  • Ah, so it's already in a usable format for your calculations. Commented Mar 20, 2012 at 19:28

2 Answers 2

1

The situation is more clear now that you posted the traceback. Thank you.

You're getting back a Decimal object.
This is just as good, in fact, better than a float.

You needn't convert it, and may simply begin your calculations:

thisout[0] += 1 # works fine

However, note that you cannot do:

thisout[0] += 1.0 # this is a TypeError

In the above case you would do instead:

import decimal as dc
thisout[0] += dc.Decimal('1.0')
Sign up to request clarification or add additional context in comments.

4 Comments

it may be better, but not for the calculation I need to do: result=sqrt(thisout[0]) TypeError: a float is required
@Pauly: for precisely this reason the Python core developers have created for you a sqrt() method. So you may simply do: result = thisout[0].sqrt()
thank you for the help. However nothing seems to work. result=thisout[0].sqrt() AttributeError: 'tuple' object has no attribute 'sqrt'
You're not using fetchone() any longer. Instead do this: thisout[0][0].sqrt()
0

If the result is simply a 1-tuple, you can access it as bernie says (and your code apparently tries) with thisout[0]. I'm guessing you're having a different error when trying to parse the float; post the stacktrace or the exception.

1 Comment

result=sqrt(thisout[0]) TypeError: a float is required

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.