Home>
About Python functions

Please write your question in detail here.
(Example) I am making a ●● system with PHP (CakePHP).
The following error message occurred while implementing the ■■ function.

def something (number):
    if number == 0:
        return 1
    else:
        return number * something (number-1)
answer = something (4)
print (answer)
Error message
24 is output, but I don't understand the reasoning
I want you to explain in an easy-to-understand manner
Applicable source code
python3
Tried

Return number * something (number-1) was changed to various numbers, but I couldn't understand

Supplemental information (FW/tool version etc.)

Please provide more detailed information here.
python3 mac

  • Answer # 1

    A factorial program using recursion.

    def something (number):
        if number == 0:
            return 1
        else:
            return number * something (number-1)
    answer = something (4)
    print (answer)
    The call to

    something (4)calculates4 * something (3). Heresomething (3)is3 * something (2). ...... Then, when1 * something (0),something (0)becomes 1, so4 * (3 * ( 2 * (1 * (1))))is calculated to be 24.

    Reference: Algorithms with Python/Recursive definition

  • Answer # 2

    This is the reason.

    2 0 LOAD_FAST 0 (number)
                  2 LOAD_CONST 1 (0)
                  4 COMPARE_OP 2 (==)
                  6 POP_JUMP_IF_FALSE 12
      3 8 LOAD_CONST 2 (1)
                 10 RETURN_VALUE
      5&​​gt;>12 LOAD_FAST 0 (number)
                 14 LOAD_GLOBAL 0 (something)
                 16 LOAD_FAST 0 (number)
                 18 LOAD_CONST 2 (1)
                 20 BINARY_SUBTRACT
                 22 CALL_FUNCTION 1
                 24 BINARY_MULTIPLY
                 26 RETURN_VALUE
                 28 LOAD_CONST 0 (None)
                 30 RETURN_VALUE


    Easy to understand!