STR Coding Club logo STR Coding ClubLearn to code, together
Teaching Code

How to Teach Recursion to Beginners Step by Step

You write a factorial function on the board, explain that it calls itself, and watch a room of beginners go quiet in the bad way.

Students standing in a line in a classroom, each tapping the shoulder of the person in front, with laptops on desks behind them

You write a factorial function on the board, explain that it calls itself, and watch a room of beginners go quiet in the bad way. If you need to teach recursion to beginners, the usual textbook route of definitions first and code second tends to lose half the group within ten minutes.

I coach problem solving at our club, and recursion is the topic that most reliably splits a room. Over a few years of sessions with teens and adults, I have settled on a sequence that gets most learners to write their own recursive function inside 90 minutes. Here it is, step by step, with the mistakes I made along the way.

Why beginners find recursion so hard

Recursion asks learners to hold two ideas at once. First, that a function can pause halfway, run a fresh copy of itself, and then carry on. Second, that this chain stops somewhere. Most beginners can follow one of those ideas, but holding both while also reading Python syntax is too much.

There is also a mental model problem. Many learners picture a function as a single box that runs once. If they think of variables as boxes too, they assume each call overwrites the last one's values. Our article on how to explain variables to beginners without the box helps here, because a learner who sees names as labels on values will find separate calls much easier to picture.

Step 1: act it out before any code

I start every recursion session away from the keyboards. Line up five volunteers. The person at the front gets asked, "How many people are behind you, including yourself?" They are not allowed to turn around and count. They can only tap the shoulder of the person behind them and ask the same question.

The last person in the line has nobody behind them, so they say "one." That answer travels back up the line, each person adding one, until the front person says "five."

This 5 minute exercise teaches three things without a single bracket:

  • Each person asks a smaller version of the same question.
  • Someone has to be able to answer without asking anyone. That is the base case.
  • The answers come back in reverse order, from the last person to the first.

Afterward, I ask the group what would happen if the last person also tried to tap someone's shoulder. Somebody always says "they would wait forever," which is a perfect intro to infinite recursion.

Step 2: teach recursion to beginners with one tiny function

Now move to code, but keep it small. I use a countdown, not factorial. A function called countdown takes a number n. If n is 0, it prints "Liftoff" and stops. Otherwise it prints n and calls countdown with n minus 1.

Countdown works well because the output is visible at every step. Learners see 3, 2, 1, Liftoff appear in order and can match each line to a call. Factorial hides its work until the very end, which makes it a poor first example.

Have everyone type the function, run it with 3, then run it with 10. Then ask them to remove the base case and run it again. Python stops with a RecursionError after about 1000 calls. Letting them hit that error on purpose turns a scary message into something familiar.

Step 3: trace the calls on paper

Once the countdown runs, hand out paper and have learners draw a stack of cards, one card per call. Each card shows the value of n for that call. When a call finishes, they cross out its card.

Then change the function so it prints after the recursive call instead of before. Now it prints 1, 2, 3. This is the moment recursion clicks for many learners, because the order flip only makes sense if each call is waiting for the one below it to finish.

I give about 15 minutes for this. Learners who struggle should trace with n equal to 2, not 5. Fewer cards means less to keep straight.

This is also a good place to practise debugging without rescuing anyone. If a trace goes wrong, ask "what is n on this card?" rather than pointing at the error. Our guide on helping a beginner debug without fixing the bug for them has more prompts like that.

Step 4: write the first recursive function solo

Give a short menu of problems and let learners pick one:

  1. Sum the numbers from 1 to n.
  2. Count how many times a letter appears in a string, one character at a time.
  3. Reverse a string by taking the first letter off and adding it to the end of the reversed rest.

Before they type, ask each learner to write two sentences on paper. One: "The base case is when..." Two: "Each call makes the problem smaller by..." If they cannot finish both sentences, they are not ready to code yet, and that is fine. Pair them with someone who has finished and let them talk it through.

In my sessions, around 70 to 80 percent of beginners finish problem 1 within 20 minutes. Problem 3 is harder and usually suits learners who already feel confident with string slicing.

Why I do not teach recursion with factorial or Fibonacci first

Almost every textbook opens with factorial, then Fibonacci. I think that is backwards for beginners. Both are maths problems first, so a learner who is shaky on maths gets two difficulties at once. Fibonacci is worse, because the naive recursive version branches into two calls and grows very slowly for even modest inputs. Calling it with 35 can take several seconds, which teaches learners that recursion is slow and confusing.

Recursion also has a reputation as an advanced trick that beginners should avoid. I disagree with that too. A learner who can trace a countdown has learned something real about how function calls work, and that pays off later when they read error tracebacks. Just keep the examples visible and small, and leave the elegant maths for later sessions.

Frequently asked questions

At what age can kids learn recursion?

Most kids around 11 or 12 can follow the line of people exercise and a countdown function. Writing their own recursive function usually comes a bit later, once they are comfortable with functions and if statements. Younger learners can still enjoy the unplugged activity on its own.

Should beginners learn loops before recursion?

Yes, in almost all cases. Loops are more common in everyday code and easier to trace. Once learners know loops, you can show that a countdown can be written both ways, which helps them see recursion as another tool rather than magic.

What is the best first recursion example?

A countdown that prints each number before calling itself is the clearest first example. It shows every step on screen and has an obvious base case. Factorial and Fibonacci work better as later exercises once the idea has settled.

SD
Selene Dragomir

Selene coaches students for programming contests. She writes about practice problems, debugging and the habits that help beginners get unstuck on their own.

More posts by Selene

More in Teaching Code

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu haskell iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven tetapatrium topselller uneplanteartificielle vipertechcr webtech1223411 wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto