0
password = '1567'
for i in range(0,10):
    for x in range (0,10):
        for y in range (0,10):
            for w in range (0,10):
                a = str(i)+str(x)+str(y)+str(w)
                print(a)
                if a == password:
                    print("Your password is: "+a)
break

I have been trying tyo make the code break once a == password please help

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • have a look at the `else` clause for `for` loops: https://book.pythontips.com/en/latest/for_-_else.html or here: https://stackoverflow.com/questions/189645/how-to-bre ak-out-of-multiple-loops or here: https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops#9980752 – hiro protagonist Oct 23 '20 at 15:47

1 Answers1

0

A single break will stop the current for loop. It will not break all the other loops.

If the current for loop is nested, it will continue the parent loop and continue looping with the next iterated value in parent loop.

You will either have to add the password checking condition in each loop and break or why don't you just return?

def find_password_brute_force(password):
    for i in range(0, 10):
        for x in range(0, 10):
            for y in range(0, 10):
                for w in range(0, 10):
                    a = str(i) + str(x) + str(y) + str(w)
                    # print(a)
                    if a == password:
                        print("Your password is: " + a)
                        return a

password = '1567'
find_password_brute_force(password=password)

PS: Using such code for nefarious purposes could land you in trouble -- don't do it.

I have shared it only for your understanding.

anurags
  • 87
  • 12