Could a GAA scoreboard count down without using a loop?
A GAA scoreboard needs to display three, two, one. You could write a loop, but could a function handle one number and hand off the rest? Watch what Python has to remember each time that handoff happens.
Start at the call to welcome. It calls double with four. Python gives that call its own frame, a space for its local values. Double returns eight. Welcome stores that result, then prints it.
Call countdown with three. Each call checks for zero first. Three prints and calls with two. Two prints and calls one. One prints and calls zero. The frame list keeps each waiting call's number. Zero returns before printing. Then one, two and three return in that order, leaving no countdown frames.
Now call the same function with two. Remember that each call checks its number before it reaches the print line. Pick exactly what you would see on the screen.
When a function calls itself like this, you're using recursion. The call with zero is the base case, where countdown returns without calling itself again. Each recursive step subtracts one from a positive integer, so you can see the arguments getting closer to zero.
Now make a function that adds the integers from one up to a non-negative integer. At zero there’s nothing to add, so return zero. For a positive number, ask for the sum up to one less. When that answer comes back, add your own number and return the total.
Call total with two. It needs the total for one, and that call needs the total for zero. Zero returns zero straight away. The call for one adds one and returns one. Finally, the call for two adds two to that returned one and gives you three.
Try total with four. Follow the calls until the argument reaches zero, then work back up. Each waiting call adds its own number once. Pick the value the original call returns.
Both versions check for zero. On the left, the next call gets one less, so three eventually reaches zero. On the right, each call gets three again. The check never succeeds, and Python eventually raises a recursion error because there are too many nested calls.
For ‘Write a recursive function to find the sum’, state what total returns and which inputs it accepts. In pseudocode, check for zero first. Otherwise, return the input plus the result for one less. Test zero for the base case, then trace three to check that your function returns six.