chknpie
chknpie

Reputation: 33

python for-loop only executes once?

import numpy as np
def Vin(t):
    inputs = []
    for i in range (1000):
        if (-1)**(np.floor( 2 * t[i] )) == 1:
            Vin = (1)
            inputs.append(Vin)
        else:
            Vin = (-1)
            inputs.append(Vin)

        return inputs

when I use this function on a range of t values, I only get one result,

i.e.

input1=Vin(tpoints)
print (input1)

only gives [1], whereas I want the function to do it for every t value.

Upvotes: 1

Views: 5197

Answers (3)

Sarath Sadasivan Pillai
Sarath Sadasivan Pillai

Reputation: 7091

You are returning from with in the for loop,So you would return from the function on first iteration of the loop.

you may re-writ e the function as following

Code

def Vin(t):
    inputs = []
    for i in range (1000):
        if (-1)**(np.floor( 2 * t[i] )) == 1:
            inputs.append(1)
        else:
            inputs.append(-1)
    return inputs

Check the indentation of return inputs in the function here .

BTW, your function can be reduced to as more pythonic and efficient code

def Vin(t):
 reduce map(lambda x:int((-1)**(np.floor( t[i] < 1))), range (1000))

Upvotes: 0

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140216

As others said, there's an indentation error in your return statement. I couldn't resist rewriting your code in a more pythonic way, avoiding all that cumbersome loops and the resulting errors:

return [1 if (-1)**(np.floor( 2 * t[i] )) == 1 else -1 for i in range (1000)]

that list comprenhension + ternary construction statement creates your -1,1 array in 1 line, much faster than you'd write with a loop.

Upvotes: 3

apomene
apomene

Reputation: 14389

try:

 for i in range (1000):
        if (-1)**(np.floor( 2 * t[i] )) == 1:
            Vin = (1)
            inputs.append(Vin)
        else:
            Vin = (-1)
            inputs.append(Vin)

 return inputs

Current indentation of return , exits the for loop after 1st iteration

Upvotes: 0

Related Questions