lewis2ba
lewis2ba

Reputation: 105

Two floats throw TypeError: unsupported operand type(s) for +: 'float' and 'str'

I am running into an issue with the following line of code:

underground['distributed_load_C'] = float(ugLineList[21])*1000 + ('+' if float(ugLineList[24]) >= 0.0 else '-') + abs(float(ugLineList[24]))*1000j

The original values pulled from ugLineList are strings and I try to type cast them into floats before addition. Even though I try to type cast them I am getting the following error:

TypeError: unsupported operand type(s) for +: 'float' and 'str'

I've tried type casting them before this statement, and checking that the code snippets are truly floats: print type(float(ugLineList[21])*1000), type(float(ugLineList[24])) ---> <type 'float'> <type 'float'>

I am really confused as to what is going on here so any help is greatly appreciated.

Thanks!!

Upvotes: 2

Views: 381

Answers (3)

MariusSiuram
MariusSiuram

Reputation: 3634

I am not sure what you are trying to do by checking the sign of the value and then performing an abs, but I would bet that you can simply drop it:

underground['distributed_load_C'] = float(ugLineList[21])*1000 + float(ugLineList[24])*1000j

Upvotes: 1

Chris
Chris

Reputation: 710

The comment above (you are adding the string '+' or '-' depending on the value of ugLineList[24]) is exactly correct. Assuming you intend to add or subtract

abs(float(ugLineList[24]))*1000j

based on the evaluation of your if statement, you could do something like:

res = float(ugLineList[21])*1000
if float(ugLineList[24]) >= 0.0:
   res += abs(float(ugLineList[24]))*1000j
else:
   res -= abs(float(ugLineList[24]))*1000j
underground['distributed_load_C'] = res   

hope this helps

Upvotes: 2

Alg_D
Alg_D

Reputation: 2390

It looks like you have strings while trying to do an aritmetic operation

+ ('+' if float(ugLineList[24]) >= 0.0 else '-')

like '+'

do you really need the condition? '+' if float(ugLineList[24]) >= 0.0

try yo cast individual variales and do the operations with them before put all in one line

Upvotes: 1

Related Questions