I'm making a small program to convert binary numbers to hexadecimal. To go about this, I first split the given data into 4 bit chunks as you can see.
def binary_to_hex(n):
if len(n)%4 != 0:
n = "0"+n
return binary_to_hex(n)
return n
Now this example works without a hitch, returning chunks of four bits.
However, when I omit the first return
statement inside the if
clause, only ever one 0
gets added. If n
is not divisible by 4, that is.
I'm guessing it has something to do with variable scope. Similar problems don't seem to apply in this case. Can you explain what is going on and how one would go about without using the first return statement.
Also, what is the name of this type of function, that calls itself until it satisfies a given requirement ?