Yusuf Kaddoura
Yusuf Kaddoura

Reputation: 1

How to stop a nested forloop after a condition is met in python

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.

Upvotes: 0

Views: 49

Answers (1)

S.B
S.B

Reputation: 16476

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

Upvotes: 1

Related Questions