title: Recursive behavior
body: <p>Why does the following executes such that the <code>print</code> statement is called as often as it recursed but the count variable, <code>count</code>, when <code>x == 1</code> is never reached.</p>
  <pre><code>def count_bits(n, count = 0):
    x = n % 2
    if n == 1:
      return count + 1
    
    if n &lt; 1:
      return count
  
    if x == 1:
      count += 1 # when x == 1
    
    count_bits(int(n/2), count)
    print(&quot;counter&quot;)
  
    return count
    
  </code></pre>
  <blockquote>
  <p>why is it necessary to recurse with the <code>return</code> statement?  Because if the recursive call is above the <code>return</code> statement the code
  returns the wrong output but with the recursive call called with
  <code>return</code> keyword, everything works well.  Typically, the <code>print</code> statement
  prints 'counter' as often as it recursed showing that the recursive call
  works.</p>
  </blockquote>
  <p>On the other hand, if &quot;return&quot; follows after the recursive call, it returns the count from the base condition, correctly.</p>
  <pre><code>def count_bits(n, count = 0):
    x = n % 2
    if n == 1:
      return count + 1
    
    if n &lt; 1:
      return count
  
    if x == 1:
      count += 1
  
    return count_bits(int(n/2), count)
  </code></pre>