"Largest power of two less than N" in Python
If what you really want is the "largest power of 2", you should make that more explicit:

def largest_power_of_two(n):


And does the largest power of two less than n mean in terms of bits? It's just dropping all of the bits except for the left-most one. Since we can get the bit length of a number directly, we can just do that:

def largest_power_of_two(n):
    return 1 &lt;&lt; (n.bit_length() - 1)


If you want error check, you can add the value error if you want (note only positive ns are valid, you initially allowed for 0... but what is the largest power of 2 less than or equal to 0?):

def largest_power_of_two(n):
    if n &gt; 0:
        return 1 &lt;&lt; (n.bit_length() - 1)
    else:
        raise ValueError("only meaningful for positive values")


Don't write loops when you don't need to.