user230307
user230307

Reputation:

Python Assignment of a Variable By Looping through a Range

The first two if statements should be identical... The first one works, the second does not work. What is wrong with the second if statement?

    row=0
    tsig=0 
    InTrade=[] 

    for data_buy in stock_data['Buy']:  

       if data_buy == 1:
           tsig=1
           print(0)
       if stock_data['Buy'][row]==1:
           tsig=1
           print (1) 

       if tsig==1:    
           InTrade.append(1)
           print(3)
       if tsig==0:
           InTrade.append(0)
           print(4)
    row=row+1    
    print(stock_data['Buy'])
    stock_data['InTrade'] = InTrade  

Upvotes: 0

Views: 43

Answers (1)

Idan Arye
Idan Arye

Reputation: 12623

row=row+1 is outside the loop. It stays 0 in each iteration of the loop, and only becomes 1 after the loop is finished.

BTW - if you want to add an iteration index to a loop, you can(and should!) use enumerate:

for row, data_buy in enumerate(stock_data['Buy']):
    # loop body...

Upvotes: 4

Related Questions