"Largest power of two less than N" in Python def floor_log(num, base):
    if num &lt; 0:
       raise ValueError("Non-negative number only.")
    exponent = 0
    while num &gt; 1:
        num &gt;&gt;= 1
        exponent += 1
    return base &lt;&lt; (exponent - 1)

print floor_log(3, 2) #2 
print floor_log(4, 2) #4
print floor_log(5, 2) #4
print floor_log(6, 2) #4


I frequently miss the edge cases like while num or while num &gt; 1. What is good strategy to avoiding these mistakes? apart from this the function seems fine to me. Comments are most welcome.
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.