So I am happily going along with my one Python student teaching him what I know of Python (admittedly not much but it is an “easy” language and I have several books to learn from). In my naive confidence that I can learn anything I decided to teach/learn more about recursion. I have this little program that converts base 10 to base 2.
- def binary(n):
- if n > 1:
- binary(n//2)
- print(n % 2,end = ”)
- dec = int(input(“Enter an integer: “))
- binary(dec)
I think I see how this works so we start to tear it apart. We are OK with the “//” and the “%” operations. Into the recursive loop we go. Surprise! I cannot figure out how it works. So I do my usual thing when I cannot figure out some code, I throw in some print statements. This method is tried and true. It has clarified code for me for many years.
- def binary(n):
- if n > 1:
- print(“first”,n) # added this for testing purposes
- binary(n//2)
- print(“second”,n) # added this for testing purposes
- print(“third” ,n % 2,end = ”)
- dec = int(input(“Enter an integer: “))
- binary(dec)
I input 22. Here is the output.
first 22
first 11
first 5
first 2
third 1second 2
third 0second 5
third 1second 11
third 1second 22
third 0
Lines 1 – 4 are just fine, the recursion loop. From there it goes to hell in a hand basket. I do not understand how it even gets to the “second” print statement. I had to call in the “Pro from Dover”, a friend of mine who teaches programming at the local university. He emailed me how it works. Nope. It still was real fuzzy. He is going to come over after the break and have a recursion sit-down with my student and I.
I actually like hitting things like this. If I knew how to do it all what fun would that be?