0

so I have been trying to stop a forloop after a condition is met. Here is the code

DATA_t = pd.read_excel('C:/Users/yo4226ka/Work Folders/Desktop/Teaching/IKER STUFF/iker1.xlsx',index_col=0, header = 0)


DATA_1 = DATA_t[["Código de Provincia","Código de Municipio","Papeletas a candidaturas"]]

cols_i= ["Código de Provincia","Código de Municipio","Papeletas a candidaturas"]

X_1  =  DATA_t["Papeletas a candidaturas"]
X_2   =  DATA_t.iloc[:,12:]
X     = pd.concat([X_1 ,X_2],axis=1)
X_b   = X.to_numpy()



X_n   = np.zeros((8070,1))  


for k in range(np.shape(X_b)[1]):
    for i in range(np.shape(X_b)[0]):
        if k==0:
            pass
        else:
            if X_b[i,0] == 0:
                pass
            elif X_b[i,k]/X_b[i,0] > 0.002:
                X_n = np.c_[X_n,X_b[:,k]]
            else:
                pass

My main issue is in the forloops below. In the ``` elif ```` statememnt i want to append a column when the condition given above is met. But, once it is met once, i want the forloop the nested forloop to stop and move on. For example say k = 1, the second forloop finds that X_b[i,1]/X_b[i,0]>0.002 and then appends that kth column to X_n. What i want now is for the loop to stop and move on to k=2 and so on. Any comment would be valuable!

I tried adding the break command after the loop but i am not sure if that does the trick.

1
  • I'm not sure what your solution is exactly because I'm not familiar with this language but you should look up labeling loops Commented Nov 8, 2022 at 14:13

1 Answer 1

1

You can use break.

Wherever you use break statement, the current loop itself exists or let's say the execution line continues after the for-loop block. Your current for-loop is the nested one so after exiting(by break) you end up running the next iteration of the "outer" for loop(since you don't have any statement after your nested for-loop, it jumps to the next iteration of the outer loop, otherwise those statements below your nested loop are gonna be executed then the next iteration of the outer loop).

for i in range(2):
    print(f"outer loop: i={i}")
    for j in range(10):
        print(f"\tinner loop: j={j}")
        if j > 1:
            break

output:

outer loop: i=0
        inner loop: j=0
        inner loop: j=1
        inner loop: j=2
outer loop: i=1
        inner loop: j=0
        inner loop: j=1
        inner loop: j=2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.