How do I pass a float as an argument in my python function

Question:

I’m trying to do a simple function; however, I receive this error: ‘float’ object is not subscriptable.

I know the float is causing the error, i’m just not sure how to handle this. Thanks in advance for any help.

# prediction probabilities
probs = [0.886,0.375,0.174,0.817,0.574,0.319,0.812,0.314,0.098,0.741,
         0.847,0.202,0.31,0.073,0.179,0.917,0.64,0.388,0.116,0.72]

# threshold value
thresh = 0.5

def predict(x,y):
    for i in x:
        if i >= y[0]:
            z.append(1)
        else:
            z.append(0)
            return(z)

predict(probs,thresh) 
Asked By: Evan Day

||

Answers:

Yes, because y, which is tresh which is set to 0.5, a float value.
Did you mean x[0]? Because this is a list.

Answered By: Ferret

Based on our conversation in the comments above, I think you are looking for something like:

def predict(x, y):
    z = []
    for i in x:
        if i >= y:
            z.append(1)
        else:
            z.append(0)
    return z

The key things to note are 1) creating z so that you can append to it 2) not having the return call inside the else body (or else it returns the very first time you end up in that body and stops going through all the elements of x).

Answered By: skumhest
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.