Mari0 Mari0 - 1 month ago 7
Python Question

Calling function f from within f

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 ?

NPE NPE
Answer

Here is the code we're discussing:

def binary_to_hex(n):
    if len(n)%4 != 0:
        n = "0"+n
        binary_to_hex(n)  # no `return'
    return n

Here, binary_to_hex(n) calls the function and ignores the result. Since the call has no observable side effects (i.e. it doesn't do anything that the caller can observe), it is effectively a no-op, and the code is equivalent to:

def binary_to_hex(n):
    if len(n)%4 != 0:
        n = "0"+n
    return n

This explains the behaviour you're seeing.

[H]ow one would go about without using the first return statement[?]

Try using a loop or the string repetition operator (*).

Comments