Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break for loop in an if statement

Tags:

Currently having trouble with breaking this for loop. I want to break it if the variable is not found in this list so it can move two another for loop. It expects an indented block for the top of the for loop, but if I change the position of the break or of the start of the for loop, it doesn't work. Help!

while cyclenumb <= 10000:

    for x in userpassword[k]:
        for z in lowercaselist:
            if x in z:
                newpasswordlist.append(z)
                k +=1
                break
        else:

    for x in userpassword[k]:
        for z in uppercaselist:
            if x in z:
                newpasswordlist.append(z)
                k +=1
                break
        else:
like image 873
mansa Avatar asked Dec 09 '16 16:12

mansa


People also ask

How do you break out of a for loop inside an if statement?

Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

Can you use break in an if statement?

The break statement ends the loop immediately when it is encountered. Its syntax is: break; The break statement is almost always used with if...else statement inside the loop.

Does break in an if statement break out of the loop?

It will break the loop (the inner most loop that the if contains in) no matter how many if statments are nested inside. A break breaks from a loop and not from if statement.

How do you stop a for loop if a condition is met?

The break statement exits a for or while loop completely. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement. break is not defined outside a for or while loop. To exit a function, use return .


1 Answers

You'll need to break out of each loop separately, as people have mentioned in the comments for your question, break only stops the loop which it's in

for x in userpassword[k]:
    for z in lowercaselist:
        if x in z:
            newpasswordlist.append(z)
            k +=1
            break
   
     if x in z: # added an extra condition to exit the main loop
        break

You'll need to do this for both loops

If you want to break out of the while loop as well, then you can add if x in z: break in that loop as well.

like image 157
Tom Fuller Avatar answered Oct 13 '22 22:10

Tom Fuller