yj lee
yj lee

Reputation: 1

How can i divide float with another float?

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

Answers (2)

Olvin Roght
Olvin Roght

Reputation: 7812

There're few issues with your code.

  1. Error occured while processing your script described in error message. You're iterating through list using indexes. Elements of this list have different types (at least str and float). If your goal is to divide two elements you need to convert both elements to float.
  2. 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):
    
  3. Error handling. As I understood list you're working with contains values of different types. I can't say for sure about this particular situation, but in general it's necessary to add exception handler to prevent loop break once error occures.

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

lapinkoira
lapinkoira

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

Related Questions