0

I have following python code

# helper function to simulate brute force attack on low entropy randomness
def simulate_brute_force_attk_key(message:str, cipher:str)->bytes:
    for k in range(2**31):
        bf_key = KeyStream(k)
        for i in range(len(message)):
            xor_value = message[i] ^ cipher[i]
            if xor_value != bf_key.get_key_byte():
                break
        else:
            return k
    return False

Above code is exectued with out error. My question how it is working when we have else part of working if corresponing if statement inside for loop where as else part is outside of inner for loop. My understanding is that both if and corresponing else part should be inside for loop. I think my understanding is wrong. Request your help in understanding this. Thanks

venkysmarty
  • 11,099
  • 25
  • 101
  • 184
  • `for`/`else` is a valid construct in python. The `else` clause executes if the `for` loop exits normally (i.e. it was not exited via a `break` statement). The same applies for `while`/`else`. – Green Cloak Guy Nov 10 '21 at 05:09
  • Does this answer your question? [Why does python use 'else' after for and while loops?](https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops) – Green Cloak Guy Nov 10 '21 at 05:10

0 Answers0