Home | | Computer Science 12th Std | Python recursive functions

Python - Python recursive functions | 12th Computer Science : Chapter 7 : Core Python : Python Functions

Chapter: 12th Computer Science : Chapter 7 : Core Python : Python Functions

Python recursive functions

When a function calls itself is known as recursion.

Python recursive functions

When a function calls itself is known as recursion. Recursion works like loop but sometimes it makes more sense to use recursion than loop. You can convert any loop to recursion.

A recursive function calls itself. Imagine a process would iterate indefinitely if not stopped by some condition! Such a process is known as infinite iteration. The condition that is applied in any recursive function is known as base condition. A base condition is must in every recursive function otherwise it will continue to execute like an infinite loop.

Overview of how recursive function works

1. Recursive function is called by some external code.

2. If the base condition is met then the program gives meaningful output and exits.

3. Otherwise, function does some required processing and then calls itself to continue recursion.

Here is an example of recursive function used to calculate factorial.

Example :

def fact(n):

if n == 0:

return 1

else:

return n * fact (n-1)

print (fact (0))

print (fact (5))

Output:

1

120

 

 

Tags : Python , 12th Computer Science : Chapter 7 : Core Python : Python Functions
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
12th Computer Science : Chapter 7 : Core Python : Python Functions : Python recursive functions | Python


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.