Since I haven’t posted since last year I figured why not show some recursion?
I know a lot of people try out something like a Fibonacci Sequence to help grasp the paradigm of recursion. I am going to do something a bit simpler. We will adapt the “Hello, World!” into a recursive function. We will play a bit with stdout in python as well.
First, here is some code:
import sys def herro(st, cnt): if cnt < len(st): sys.stdout.write(st[cnt]) cnt += 1 herro(st, cnt) return herro('Hello, World!\n', 0)
First, we import sys so we can use stdout. Then we define our function that shall call itself. We have two parameters, one for the string itself, and one to check for recursion depth. If we didn’t have the “if” statement in there it would call itself forever and end up running out of memory. We then use stdout to write directly to the shell. We do this because print() would append a newline to each iteration of the function. Add one to cnt so we don’t go further than the length of string we’re printing. At the end, return nothing to exit the function.
You might be wondering why I added a newline char (\n) to the end of the string we supplied. I did that for formatting only. If there was no newline at the end, we would see the results before the prompt and it doesn’t look too well. Go ahead and remove the newline to see what happens.