Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Asher Orr
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Asher Orr
Python Development Techdegree Graduate 9,409 Points

Understanding how a recursive function works: I need help!

Hi everyone! I have a recursive function, DecimalToBinary:

def DecimalToBinary(num):
    if num >= 1:
        DecimalToBinary(num // 2)
        print(num % 2, end = '')

I need help understanding exactly what is happening in line 3. Here's what I think is happening:

def DecimalToBinary(num):
    if num >= 1:
    # if the argument is greater than or equal to 1, then:
        DecimalToBinary(num // 2)
        # call the DecimalToBinary Function
        # this is going to divide the num by 2, using floor division
        print(num % 2, end = '')
        # then use a modulo operation to find the remainder of num
        # in the print statement, num now represents the result of DecimalToBinary(num // 2)
       # and print it in one line.

Here's an example using the integer 3 as an argument:

def DecimalToBinary(3):
    if num >= 1:
        DecimalToBinary(3 // 2)
        print(1.5 % 2, end = '')

.. In this case, the function prints the integer 11.

Am I on the right track here? If not, can anyone help me understand how this function works?

1 Answer

Steven Parker
Steven Parker
231,248 Points

It sounds like you have the basic idea. For better understanding, you might try making a list of operations (just outputs and calls) performed and maybe start with a slightly larger number so you can see more than 2 levels of recursion. List the level along with the operation at each step:

Level Operation
  0   DecimalToBinary(5)
  1     DecimalToBinary(2)
  2       DecimalToBinary(1)
  3         print(1)
  2       print(0)
  1     print(1)