Ask Your Question
2

How can I display the final result returned by my recursive function for calculating the factorial of an n number within a sub function in my code?

asked 2023-06-07 10:49:45 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-07 11:08:02 +0000

qstack gravatar image

You can display the final result returned by your recursive function in two ways within a sub function:

  1. You can use the print() function to print the final result returned by your recursive function. For example:
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

def calculate_factorial(n):
    result = factorial(n)
    print("The factorial of ", n, " is: ", result)

calculate_factorial(5)

Output:

The factorial of  5  is:  120
  1. You can return the final result from the recursive function and assign it to a variable within the sub function, and then use the print() function to print the result. For example:
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

def calculate_factorial(n):
    result = factorial(n)
    return result

final_result = calculate_factorial(5)
print("The factorial of 5 is: ", final_result)

Output:

The factorial of 5 is: 120
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-07 10:49:45 +0000

Seen: 20 times

Last updated: Jun 07 '23