Tuesday, 24 January 2017

RECURSIVE FUNCTION CALL IN PYTHON

The concept of calling one function by the same function is known as recursive function calling.

Example –
def recur_fact(x):
    """ This is a recursive function to find
    factorial of an integer """
    if x==1:
        return 1
    else:
        return x*recur_fact(x-1)
num=input('Enter a number : ')
if num>=1:
    print 'The factorial of ',num,'is ',recur_fact(num)

Output –
Enter a number : 5

The factorial of  5 is  120



Note – Infinite recursion is not supported by python. It will terminate with an error.

Example –
def f1():
    print 'in f1'
    f1()
f1()

Output –
in f1
in f1
in f1
----
----
----
File "C:/Users/om/PycharmProjects/Pythonn/if3.py", line 3, in f1
f1()

No comments:

Post a Comment