A function can call itself! I.e., in the definition of a function, we can write a call to the function itself. This is a powerful idea that is seen throughout computer science and we will give you an introduction over a 2-lecture sequence. So be patient as you learn this new concept. Learn a little, digest the idea for a few days, and learn more next lecture.

Lessons - watch before lecture

  1. Recursive Definitions (6 minutes) Warm up with some examples in mathematics: the factorial and the Fibonacci sequence
  2. Recursive Functions (6 minutes) A recursive function to compute the factorial of a number n

AND read 5.8 - 5.10

Lecture materials

Slides: individual slides for viewing, 6-up layout for printing

Examples: factorial.py, playWithDolls.py, russian.py (module to provide class Doll--you don't need to understand or even read the code), blastoff.py, num_es.py, deblank.py
To download the above .py files, right-click (Windows) or command-click (Macs) on the filename and then select "Save link as".
This way you choose where the files will be saved, instead of having your computer save to the default folder (from which you will later have to move your files for organization).

Lecture Recording (The first half-minute of the lecture was missed unfortunately.)

Post-lecture activity: As announced during lecture, please play with the code discussed today (see files above). In order to learn how recursive functions work, you need think about and observe how the call stack grows and shrinks during program execution. Just watching what was done in lecture is not enough. Be sure to (modify) and run the code yourself, in the terminal and in Python Tutor. See the instructions on these slides (15, 50, 64).