Intro to Python Programming

study guides for every class

that actually explain what's on your next test

Recursion

from class:

Intro to Python Programming

Definition

Recursion is a programming technique where a function calls itself to solve smaller instances of the same problem. It typically involves a base case to terminate the recursive calls and prevent infinite loops.

congrats on reading the definition of Recursion. now let's actually learn it.

ok, let's learn stuff

5 Must Know Facts For Your Next Test

  1. A recursive function must have a base case that stops the recursion.
  2. Each recursive call should progress towards the base case.
  3. Stack overflow can occur if there are too many recursive calls without reaching the base case.
  4. Recursion can often be replaced with iteration, but recursion is more natural for problems like tree traversal and factorial calculation.
  5. Python has a default recursion limit, which can be checked and modified using sys.getrecursionlimit() and sys.setrecursionlimit().

Review Questions

  • What is a base case in recursion?
  • How does Python handle excessive recursive calls?
  • Can all recursive algorithms be converted into iterative ones? Provide an example.
© 2024 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.
Glossary
Guides