简体   繁体   中英

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 ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM