简体   繁体   English

从f内调用函数f

[英]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. 为此,我首先将给定的数据分为4位块,如您所见。

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子句中的第一个return语句时,只会添加一个0 If n is not divisible by 4, that is. 如果n不能被4整除,那就是。

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. 您能否解释一下发生的情况以及在不使用第一个return语句的情况下将如何进行。

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 . 在这里, binary_to_hex(n)调用该函数并忽略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[?] [H]现在不用第一个return语句就可以解决[[]

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 : 如果要不递归地实现此功能,请将if替换为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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