
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How can we create recursive functions in Python?
Recursion is a programming technique, in which a function calls itself one or more times in its body. Usually, it is returning the return value of this function call. If a function definition follows recursion, we call this function a recursive function.
A recursive function has to be terminated before it can be used in a program. It terminates, if, with every recursive call, the solution of the problem becomes smaller and moves towards a base case, where the problem can be solved without further recursion. A recursion can lead to an infinite loop, if the base case is not met in the calls.
We use recursive functions in Python to solve real world math problems.
Sum of First n Natural Numbers
The following code returns the sum of the first n natural numbers using a recursive Python function.
Example
This prints the sum of first 100 natural numbers and first 500 natural numbers
def sum_n(n): if n== 0: return 0 else: return n + sum_n(n-1) print(sum_n(100)) print(sum_n(500))
Output
5050 125250
Factorial Function Using Recursion
A recursive function is one that calls itself repeatedly until it reaches a base case where the recursion stops. Let us consider an example of a simple recursive function in Python that calculates the factorial of a given number
Here, the factorial function takes a positive integer n as an argument and returns the factorial of that number. If n is equal to 0, then the function returns 1, which is the base case. Otherwise, the function calls itself recursively with the argument n-1 and multiplies the result by n. The recursion continues until the base case is reached.
Example
This will call the factorial function with an argument of 5, which will return 5 * 4 * 3 * 2 * 1 = 120.
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) print(factorial(5))
Output
120
Fibonacci Sequence Using Recursion
Here in this example, the Fibonacci function takes a non-negative integer n as an argument and returns the nth number in the Fibonacci sequence. If n is equal to 0, the function returns 0. If n is equal to 1, the function returns 1. Otherwise, the function calls itself recursively with arguments n-1 and n-2 and returns the sum of the results. The recursion continues until the base case is reached.
Example
This will call the Fibonacci function with an argument of 6, which will return the 6th number in the Fibonacci sequence, which is 8.
def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(6))
Output
8
How to find the GCD of numbers:
Another example of a recursive function in Python that finds the greatest common divisor (GCD) of two positive integers is as follows
In this example, the gcd function takes two positive integers a and b as arguments and returns their greatest common divisor. If b is equal to 0, the function returns a, which is the base case. Otherwise, the function calls itself recursively with the arguments b and a % b, where % is the modulus operator, and returns the result. The recursion continues until the base case is reached.
Example
This will call the gcd function with arguments of 24 and 36, which will return their greatest common divisor, which is 12.
def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) print(gcd(24, 36))
Output
12
Calculate the sum of digits of a positive integer:
In this example, the sum_digits function takes a positive integer n as an argument and returns the sum of its digits. If n is less than 10, the function returns n, which is the base case. Otherwise, the function adds the last digit of n to the sum of the digits of n divided by 10 using integer division (// operator) and calls itself recursively with the result. The recursion continues until the base case is reached.
Example
This will call the sum_digits function with an argument of 12345, which will return the sum of its digits, which is 1 + 2 + 3 + 4 + 5 = 15.
def sum_digits(n): if n < 10: return n else: return n % 10 + sum_digits(n // 10) print(sum_digits(12345))
Output
15
Find the length of a string
In this example, the string_length function takes a string s as an argument and returns its length. If s is an empty string (''), the function returns 0, which is the base case. Otherwise, the function adds 1 to the length of the string obtained by slicing the first character (s[0]) and calling the string_length function recursively with the remaining string (s[1:]). The recursion continues until the base case is reached.
Example
def string_length(s): if s == '': return 0 else: return 1 + string_length(s[1:]) print(string_length('hello world'))
Output
11
This will call the string_length function with an argument of 'hello world', which will return its length, which is 11.
Recursive functions can be a powerful and elegant solution to certain types of problems, but they can also lead to infinite recursion if not designed properly. It's important to carefully consider the base case and ensure that the function will eventually reach it.
- Related Articles
- How can we create recursive functions in Python?
- How we can store Python functions in a Sqlite table?
- What are MySQL stored functions and how can we create them?
- How we can create singleton class in Python?
- How can we combine functions in MySQL?
- Do recursive functions in Python create a new namespace each time the function calls itself?
- How we can create a dictionary from a given tuple in Python?
- How can we calculate the Date in MySQL using functions?
- How can we create MySQL views?
- Auxiliary Space with Recursive Functions in C Program?
- How can we distinguish between MySQL IFNULL() and NULLIF() functions?
- How can we create multicolumn UNIQUE indexes?
- How can we create a custom exception in Java?
- How do we create multiline comments in Python?
- How to create a simple Recursive Function in Golang?
- How can we create user accounts in MySQL database server?
