---
title: "Python: A Neat Way to Write Recursive Functions"
description: "Here are the examples to create recursive functions in Python, which can be helpful for interviews and projects for quick reference"
url: https://srinimf.com/2023/08/05/how-to-write-recursive-functions-in-python/
date: 2023-08-05
modified: 2026-10-10
author: "Srini"
image: https://i0.wp.com/srinimf.com/wp-content/uploads/2023/08/python-recursive-functions.jpg?fit=2240%2C1260&ssl=1
categories: ["Python"]
tags: ["Python Recursive Examples"]
type: post
lang: en
---

# Python: A Neat Way to Write Recursive Functions

Recursive Functions in Python are tools that solve problems by breaking them down into smaller parts through self-calling.

Table of contents

1. [Python recursive function](https://srinimf.com/2023/08/05/how-to-write-recursive-functions-in-python/#python-recursive-function)
2. [Recursion examples](https://srinimf.com/2023/08/05/how-to-write-recursive-functions-in-python/#recursion-examples)
   1. [Factorial recursion](https://srinimf.com/2023/08/05/how-to-write-recursive-functions-in-python/#factorial-recursion)
   2. [The sum of N numbers](https://srinimf.com/2023/08/05/how-to-write-recursive-functions-in-python/#03-sum-of-n-numbers-recursive-function-python)
3. [Conclusion](https://srinimf.com/2023/08/05/how-to-write-recursive-functions-in-python/#conclusion)

![Recursive Functions in Python](https://i0.wp.com/srinimf.com/wp-content/uploads/2023/08/pexels-photo-4855385.jpeg?resize=1880%2C1253&ssl=1)*Photo by Cottonbro Studio on Pexels.com*

## [Python recursive](https://srinimf.com/2024/10/19/10-must-practice-python-recursive-programs/) function

**Advantages**

To solve complex problems, recursive functions are used by breaking them into smaller parts. They can be helpful for tasks such as searching, sorting, and navigating data structures.

**Disadvantages**

[Recursive functions](https://realpython.com/python-recursion/) can be powerful, but they need to be used carefully. If not designed well, they can use up a lot of memory and processing power. They can also cause program crashes or go into endless loops if not implemented correctly.

## Recursion examples

### Factorial recursion

```
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)
result = factorial(5)
print(result)
```

Output

```
120
** Process exited - Return Code: 0 **
Press Enter to exit terminal
```

In this example, the recursive function `factorial` calculates the factorial of a given number (n). The base case is when `n` is equal to 0, in which case the function returns 1. Otherwise, it multiplies `n` with the factorial of(n-1). The function is called with, and the result is printed, giving us the factorial of 5, which is 120.

> Python Tips:—————-The with statement would be useful whenever there are related operations block on each other.with expression : with-blockIn the above statement, we see that with block would be used within the context of variable opened with the help of with statement.with open(‘output.txt’, ‘w’) as f: f.write(‘|Python!’)In the above example, the file would be closed as soon as the scope of with block gets over the advantage of being not to close the file explicitly using close block.

**Python Shortcut **

```
factorial = lambda n: n if n == 1 else n * factorial(n - 1)
print(factorial(6))
```

Output

```
720
** Process exited - Return Code: 0 **
Press Enter to exit terminal
```

### The sum of N numbers

Calculation of the sum in Python Again, you convert the [recursive calculation formula](https://srinimf.com/2023/05/07/12-essential-pandas-python-interview-questions/) of the summation into a recursive function:

```
def sum_of(n):
    if n <= 0:
        raise ValueError("n must be >= 1")
    # recursive termination
    if n == 1:
        return 1
    # recursive descent
    return n + sum_of(n - 1)
    
print(sum_of(10))
```

Output

```
55
** Process exited - Return Code: 0 **
Press Enter to exit terminal
```

Python shortcut

For the calculation of sums, it is possible to use a lambda, but again without error handling and a bit less readable:

```
sum_of = lambda n: n if n == 1 else n + sum_of(n - 1)
print(sum_of(10))
```

Output

```
55
** Process exited - Return Code: 0 **
Press Enter to exit terminal
```

## Conclusion

In this article, we explored two examples of recursive functions in Python. The first example showed how to calculate the factorial of a number using recursion. We defined a base case and a recursive step to compute the factorial.

The second example demonstrated how to calculate the sum of N numbers using recursion. Again, we defined a base case and used recursion to compute the sum.

Python also provides shortcuts for recursive functions using lambda expressions. While they can be concise, it’s important to consider readability and error handling when using them.

In conclusion, recursive functions in Python are a powerful tool for solving complex problems. By breaking problems into smaller parts, we can write elegant and efficient code.

### Share this:

-
- [Tweet](https://twitter.com/share)
- [![](https://i0.wp.com/assets.pinterest.com/images/pidgets/pinit_fg_en_rect_gray_20.png)](https://www.pinterest.com/pin/create/link/?url=https%3A%2F%2Fsrinimf.com%2F2023%2F08%2F05%2Fhow-to-write-recursive-functions-in-python%2F&media=https%3A%2F%2Fi0.wp.com%2Fsrinimf.com%2Fwp-content%2Fuploads%2F2023%2F08%2Fpython-recursive-functions.jpg%3Ffit%3D1200%252C675%26ssl%3D1&description=Python%3A%20A%20Neat%20Way%20to%20Write%20Recursive%20Functions)
-
- [Share on Tumblr](https://www.tumblr.com/share)
- [Share on WhatsApp (Opens in new window) WhatsApp](https://srinimf.com/2023/08/05/how-to-write-recursive-functions-in-python/?share=jetpack-whatsapp)
- [More](#)
-

- [Print (Opens in new window) Print](https://srinimf.com/2023/08/05/how-to-write-recursive-functions-in-python/?share=print)
- [Share on Reddit (Opens in new window) Reddit](https://srinimf.com/2023/08/05/how-to-write-recursive-functions-in-python/?share=reddit)
- [Share on Telegram (Opens in new window) Telegram](https://srinimf.com/2023/08/05/how-to-write-recursive-functions-in-python/?share=telegram)
- [Email a link to a friend (Opens in new window) Email](mailto:?subject=%5BShared%20Post%5D%20Python%3A%20A%20Neat%20Way%20to%20Write%20Recursive%20Functions&body=https%3A%2F%2Fsrinimf.com%2F2023%2F08%2F05%2Fhow-to-write-recursive-functions-in-python%2F&share=email)
-

### Like this:

Like Loading…
