Reputation: 1
When I'm trying to divide float with another float, "unsupported operand type(s) for /: 'str' and 'float'" error occurs. but, I have to divide float with another float...
for k in range(0, len(diff2_list)):
xt_d2 = diff2_list[k]
if k==0 or k==(len(diff2_list)-1):
spkd_c2_list.append("NAN")
else:
spkd_c2_list.append((diff2_list[k-1])/(diff2_list[k+1]))
every values in list diff2_list
are float
I expected the result of some float value. but as I told before, "unsupported operand type(s) for /: 'str' and 'float'" error occurs.
How can I solve this problem?
Upvotes: 0
Views: 88
Reputation: 7812
There're few issues with your code.
str
and float
). If your goal is to divide two elements you need to convert both elements to float
.You're not using range()
properly. First of all, range(0, len(diff2_list))
equivalent to range(len(diff2_list))
. But if we will look in code inside loop we will find next condition: if k==0 or k==(len(diff2_list)-1):
. You've added this to avoid errors while accesing indexes which are out of list. But you can prevent it by determinating range excluding indexes of first and last elements of list.
for k in range(1, len(diff2_list) - 1):
So applying all this tips your code will look like this:
diff2_list = [1, 1.1, "1.2", "1.3"]
spkd_c2_list =[]
for k in range(1, len(diff2_list) - 1):
xt_d2 = diff2_list[k] # if you need it, cause in current code you don't use it
try:
spkd_c2_list.append(float(diff2_list[k - 1]) / float(diff2_list[k + 1]))
except:
spkd_c2_list.append("NAN")
Upvotes: 1
Reputation: 8988
Unsupported operand types means one of your types is not a float but a str (string), just make sure your operands are floats:
spkd_c2_list.append(float(diff2_list[k-1])/float(diff2_list[k+1]))
Upvotes: 0