Python ProgrammingPython Programming

Mechanics of a recursive function

A function that calls itself is known as a recursive function. A problem can be solved with recursion if it can be broken down into smaller problems that are identical in structure to the overall problem. Find factorial of a number and generate series of numbers using recursion.
##
# Python's program to demonstrate use of recursion functions.


def main():
    # Get a number from user.
    user_num = int(input("Enter any positive interger: "))

    # Get the factorial of the number.
    fact = factorial(user_num)

    # Display the output
    print("The factorial of ", user_num, " is ", fact)

    # Generate Fibonacci Series upto user input
    print("\n####################################")
    print("Fibonacci Series of first", user_num, " numbers.")
    for fib_num in range(1, user_num):
        print(fibonacci(fib_num))


# The factorial function uses recursion to calculate
# the factorial of a number.
def factorial(num):
    if num == 0:
        return 1
    else:
        return num * factorial(num - 1)


# The fibonacci function returns the nth number
# in the Fibonacci series.
def fibonacci(num):
    if num == 0:
        return 0
    elif num == 1:
        return 1
    else:
        return fibonacci(num - 1) + fibonacci(num - 2)


main()

Sample output of above program.
C:\Python\programs>pep8 --first recursion.py

C:\Python\programs>python recursion.py
Enter any positive interger: 5
The factorial of 5 is 120

####################################
Fibonacci Series of first 5 numbers.
1
1
2
3

C:\Python\programs>