w3resource

Python Data Structures and Algorithms - Recursion: Factorial of a non-negative integer


Write a Python program to get the factorial of a non-negative integer using recursion.

Sample Solution:

Python Code:

# Define a function named factorial that calculates the factorial of a given number 'n'
def factorial(n):
    # Check if 'n' is less than or equal to 1
    if n <= 1:
        # If 'n' is 1 or less, return 1 (base case for factorial)
        return 1
    else:
        # If 'n' is greater than 1, recursively call the factorial function
        # to calculate the factorial of (n - 1) and multiply the result by 'n'
        return n * factorial(n - 1)

# Print the result of calling the factorial function with the input value 5
print(factorial(5))

Sample Output:

120

Flowchart:

Flowchart: Recursion: Factorial of a non-negative integer.

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program of recursion list sum.
Next: Write a Python program to solve the Fibonacci sequence using recursion.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.