0

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 ?

Community
  • 1
  • 1
Mario Geuenich
  • 294
  • 1
  • 7
  • 17
  • 8
    It's called a recursive function. –  Oct 21 '16 at 15:34
  • 2
    that's not a "binary number". it's a string, and all you're doing is zero-padding it. and the name would be "recursive". **ANY** function which calls itself directly (or indirectly) is recursive. – Marc B Oct 21 '16 at 15:35
  • I left the binary to string conversion out for simplicity sake. In any case, it is just a sequence of 0's and 1's. – Mario Geuenich Oct 21 '16 at 15:36
  • For more info on recursive functions: http://stackoverflow.com/questions/3021/what-is-recursion-and-when-should-i-use-it – Random Davis Oct 21 '16 at 15:48

2 Answers2

1

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 (*).

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Should it not however make changes to the argument n ? My understanding is that n can be treated like a variable, say you make the same changes to a variable that is defined before this function is called, would it not output something else ? – Mario Geuenich Oct 21 '16 at 15:44
  • "Should it not however make changes to the argument n ? " Every **call to** the function (even if other calls are in progress) has its own `n`. – Karl Knechtel Sep 11 '22 at 11:08
0

As has been stated in the comments already, a function calling itself is called recursive.

If you want to implement this function without recursion, replace the if with a while:

def add_leading_zeros_to_make_length_of_string_a_multiple_of_four(n):
    while len(n)%4 != 0:
        n = "0"+n
    return n
jakun
  • 624
  • 5
  • 13