{"id":56,"date":"2024-01-24T14:30:37","date_gmt":"2024-01-24T14:30:37","guid":{"rendered":"https:\/\/learnpython.elegantwallp.com\/?p=56"},"modified":"2024-01-24T14:30:39","modified_gmt":"2024-01-24T14:30:39","slug":"python-recursive-functions","status":"publish","type":"post","link":"https:\/\/learnpython.elegantwallp.com\/2024\/01\/24\/python-recursive-functions\/","title":{"rendered":"Python Recursive Functions"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you\u2019ll learn about Python recursive functions and how to use them to simplify your code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to recursive functions<\/h2>\n\n\n\n<p>A recursive function is a\u00a0function\u00a0that calls itself until it doesn\u2019t.<\/p>\n\n\n\n<p>The following\u00a0<code>fn()<\/code>\u00a0function is a recursive function because it has a call to itself:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def fn(): <em># ...<\/em> fn() <em># ...<\/em> <\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>In the&nbsp;<code>fn()<\/code>&nbsp;function, the&nbsp;<code>#...<\/code>&nbsp;means other code.<\/p>\n\n\n\n<p>Also, a recursive function needs to have a condition to stop calling itself. So you need to add an\u00a0if statement\u00a0like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def fn(): <em># ...<\/em> if condition: <em># stop calling itself<\/em> else: fn() <em># ...<\/em> <\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Typically, you use a recursive function to divide a big problem that\u2019s difficult to solve into smaller problems that are easier to solve.<\/p>\n\n\n\n<p>In programming, you\u2019ll often find the recursive functions used in data structures and algorithms like trees, graphs, and binary searches.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Python recursive function examples<\/h2>\n\n\n\n<p>Let\u2019s take some examples of using Python recursive functions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1) A simple recursive function example in Python<\/h3>\n\n\n\n<p>Suppose you need to develop a countdown function that counts down from a specified number to zero.<\/p>\n\n\n\n<p>For example, if you call the function that counts down from 3, it\u2019ll show the following output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>3 2 1<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The following defines the\u00a0<code>count_down()<\/code>\u00a0function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def count_down(start): \"\"\" Count down from a number \"\"\" print(start)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>If you call the\u00a0<code>count_down()<\/code>\u00a0function now:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>count_down(3)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>\u2026it\u2019ll show only the number 3.<\/p>\n\n\n\n<p>To show the numbers 3, 2, and 1, you need to:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, call the&nbsp;<code>count_down(3)<\/code>&nbsp;to show the number 3.<\/li>\n\n\n\n<li>Second, call the&nbsp;<code>count_down(2)<\/code>&nbsp;to show the number 2.<\/li>\n\n\n\n<li>Finally, call the&nbsp;<code>count_down(1)<\/code>&nbsp;to show the number 1.<\/li>\n<\/ul>\n\n\n\n<p>In order to do so, inside the&nbsp;<code>count_down()<\/code>&nbsp;function, you\u2019ll need to define a logic to call the function&nbsp;<code>count_down()<\/code>&nbsp;with argument 2, and 1.<\/p>\n\n\n\n<p>To do it, you need to make the&nbsp;<code>count_down()<\/code>&nbsp;function recursive.<\/p>\n\n\n\n<p>The following defines a recursive\u00a0<code>count_down()<\/code>\u00a0function and calls it by passing the number 3:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def count_down(start): \"\"\" Count down from a number \"\"\" print(start) count_down(start-1) count_down(3)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>If you execute the program, you\u2019ll see the following error:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>RecursionError: maximum recursion depth exceeded while calling a Python object<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The reason is that the&nbsp;<code>count_down()<\/code>&nbsp;calls itself indefinitely until the system stops it.<\/p>\n\n\n\n<p>Since you need to stop counting down the number reaches zero. To do so, you add a condition like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def count_down(start): \"\"\" Count down from a number \"\"\" print(start) <em># call the count_down if the next<\/em> <em># number is greater than 0<\/em> next = start - 1 if next > 0: count_down(next) count_down(3)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>3 2 1<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>In this example, the&nbsp;<code>count_down()<\/code>&nbsp;function only calls itself when the next number is greater than zero. In other words, if the next number is zero, it stops calling itself.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">2) Using a recursive function to calculate the sum of a sequence<\/h2>\n\n\n\n<p>Suppose that you need to calculate a sum of a sequence e.g., from 1 to 100. A simple way to do this is to use a\u00a0for loop with the range() function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def sum(n): total = 0 for index in range(n+1): total += index return total result = sum(100) print(result)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>5050<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>To apply the recursion technique, you can calculate the sum of the sequence from 1 to n as follows:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>sum(n) = n + sum(n-1)<\/li>\n\n\n\n<li>sum(n-1) = n-1 + sum(n-2)<\/li>\n\n\n\n<li>\u2026<\/li>\n\n\n\n<li>sum(0) = 0<\/li>\n<\/ul>\n\n\n\n<p>The&nbsp;<code>sum()<\/code>&nbsp;function keeps calling itself as long as its argument is greater than zero.<\/p>\n\n\n\n<p>The following defines the recursive version of the\u00a0<code>sum()<\/code>\u00a0function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def sum(n): if n > 0: return n + sum(n-1) return 0 result = sum(100) print(result)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>As you can see, the recursive function is much shorter and more readable.<\/p>\n\n\n\n<p>If you use the\u00a0ternary operator, the\u00a0<code>sum()<\/code>\u00a0will be even more concise:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def sum(n): return n + sum(n-1) if n > 0 else 0 result = sum(100) print(result)<\/code><\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Summary: in this tutorial, you\u2019ll learn about Python recursive functions and how to use them to simplify your code. Introduction to recursive functions A recursive function is a\u00a0function\u00a0that calls itself until it doesn\u2019t. The following\u00a0fn()\u00a0function is a recursive function because it has a call to itself: In the&nbsp;fn()&nbsp;function, the&nbsp;#&#8230;&nbsp;means other code. Also, a recursive function [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[18],"tags":[],"class_list":["post-56","post","type-post","status-publish","format-standard","hentry","category-4-functions"],"_links":{"self":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/56","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/comments?post=56"}],"version-history":[{"count":1,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/56\/revisions"}],"predecessor-version":[{"id":57,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/56\/revisions\/57"}],"wp:attachment":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/media?parent=56"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/categories?post=56"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/tags?post=56"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}