Python Forum
How to break out of nested loops
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to break out of nested loops
#1
I'm struggling with a piece of code that I am writing for a computer security course.
I am trying to write a piece of test code that test a 4 digit password based on the time to resolve.

I want to start with a pw of 4 numbers all 0's. For each digit, test the number 0 through to 9.
If the I get a response back from a function that is greater than 0.2sec, then alter the pw list with that digit, then move onto the next one.

However my code is not incrementing through the list. I tried simply inserting a break after my if statement, but realized I also have to break our of the outer "for loop", i tried inserting a break here, but still cant get my code to work.

What Am I missing?

import time
import sys # ignore

sys.path.insert(0,'.') # ignore
real_password = '2234'

#This function cannot be changed
def check_password(password): # Don't change it
    if len(password) != len(real_password):
        return False
    for x, y in zip(password, real_password):
        time.sleep(0.1) # Simulates the wait time of the safe's mechanism
        if int(x) != int(y):
            return False
    return True



def crack_password():
    pw = [0,0,0,0]
    cnt = 0
    if cnt < 3:
        for i in range (0,9):
            pw[cnt] = i
            start = time.time()
            check_password(create_string(pw))
            stop = time.time()
            t_time = stop - start
            print(pw[cnt], t_time)
            if t_time > 0.2:
                cnt +=1
                {break out of the loop and move to the next digit}
                #Struggling with my code here!


#Creates a string from the list
def create_string(pw_list):
    string = ''
    for char in pw_list:
        string += str(char)
    return string
My print statement in the crack_password function provides:

0 0.10016393661499023
1 0.10017132759094238
2 0.1006174087524414
3 0.10022568702697754
4 0.1002652645111084
5 0.20053935050964355
6 0.10025167465209961
7 0.10107183456420898
8 0.10021018981933594

Thus I know that the first number of the password is 5, as it is greater than 0.2. How can I then break from this loop and move to the next iteration of the pw integer? I'm also interested in how other would solve this issue.
Reply
#2
You need an outer loop to repeat the cracking code foor each digit of the 4 digit code. Break will do exactly what you want for the "inner" loop, ending the search for a digit and moving on to the next.
Reply
#3
(Mar-03-2021, 12:29 PM)deanhystad Wrote: You need an outer loop to repeat the cracking code foor each digit of the 4 digit code. Break will do exactly what you want for the "inner" loop, ending the search for a digit and moving on to the next.

Thanks for the response, I just added an extra line of code, an if statement under the for loop. This is the line of code I am having trouble breaking out of, as i need to also break out of the for loop after this.
Reply
#4
Why aren't you using a for loop for the outer loop?

Don't change code in your posts. Make a new post for the modified code. Otherwise conversations that reference code get really confusing when the referenced code no longer exists.
Reply
#5
Yes agreed, an outside for loop would be better, how do I break these loops once the if statement is matched?

def crack_password():
    pw = [0,0,0,0]
    for x in range(4):
        for i in range (0,9):
            pw[x] = i
            start = time.time()
            check_password(create_string(pw))
            stop = time.time()
            t_time = stop - start
            #print(pw[x], t_time)
            if t_time > 0.2:
                break
   
            
    print(pw)
Reply
#6
break? Just like you are doing?
Reply
#7
(Mar-03-2021, 04:42 PM)deanhystad Wrote: break? Just like you are doing?

That doesn't work, as it only breaks the inner loop and doesn't reset the loop for the next iteration.
Reply
#8
You only want to break out of the inner loop. You want the outer loop to run until it finds all 4 numbers. And it does reset the inner loop for the next iteration.

This comment is in your code "break out of the loop and move to the next digit"

And this code does exactly that.
            if t_time > 0.2:
                break
Reply
#9
(Mar-03-2021, 05:12 PM)deanhystad Wrote: You only want to break out of the inner loop. You want the outer loop to run until it finds all 4 numbers. And it does reset the inner loop for the next iteration.

This comment is in your code "break out of the loop and move to the next digit"

And this code does exactly that.
            if t_time > 0.2:
                break

The problem is that it also needs to break the next for loop that is still iterating over the numbers 0-9
If I don't break this then, for example I find the number 5, break out, and the outer loop continues form 6 onwards.
Reply
#10
I don't know where you get that idea. When you break out of the inner loop it finishes the code in the outer loop (in your example there is none) and begins the next iteration in the outer loop. When the outer loop encounters the inner for loop it starts the inner for loop from the beginning (0). It cannot continue the inner loop where the inner loop left off because there is no mechanism to remember where the for loop left off when it was broken.

A simple example:
import random

for a in '1234':
    for b in 'abcd':
        print (a, b)
        if b == random.choice('abcd'):
            break
Output:
1 a 1 b 1 c 2 a 2 b 2 c 2 d 3 a 4 a 4 b 4 c 4 d
Notice that each time the outer loop changes (1, 2, 3, 4) that the inner loop restarts at "a". This is what your code will do. Each time you find a new digit for "pw", the inner loop will start over at 0.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  for loops break when I call the list I'm looping through Radical 4 903 Sep-18-2023, 07:52 AM
Last Post: buran
  reduce nested for-loops Phaze90 11 1,920 Mar-16-2023, 06:28 PM
Last Post: ndc85430
  Nested for loops: Iterating over columns of a DataFrame to plot on subplots dm222 0 1,726 Aug-19-2022, 11:07 AM
Last Post: dm222
  Nested for loops - help with iterating a variable outside of the main loop dm222 4 1,605 Aug-17-2022, 10:17 PM
Last Post: deanhystad
  breaking out of nested loops Skaperen 3 1,233 Jul-18-2022, 12:59 AM
Last Post: Skaperen
  Break out of nested loops muzikman 11 3,375 Sep-18-2021, 12:59 PM
Last Post: muzikman
  Nested for Loops sammay 1 8,772 Jan-09-2021, 06:48 PM
Last Post: deanhystad
  How to make this function general to create binary numbers? (many nested for loops) dospina 4 4,433 Jun-24-2020, 04:05 AM
Last Post: deanhystad
  Conditionals, while loops, continue, break (PyBite 102) Drone4four 2 2,993 Jun-04-2020, 12:08 PM
Last Post: Drone4four
  Python beginner - nested while loops mikebarden 1 1,880 Jun-01-2020, 01:04 PM
Last Post: DPaul

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020