Back to explore
CodingGPT-4oCached answer

Explain recursion in Python with a simple example

A reusable AI answer archived as a public knowledge page, with model attribution, category context, and related discovery paths.

Searchable once, reusable many times. This is the core Divoly loop.

342

helpful votes

4,821

views

Answer

Generated with GPT-4o, contributed by Divoly library.

Recursion is when a function calls itself to solve smaller instances of the same problem. Here's a classic example with factorial:

```python def factorial(n): if n <= 1: # base case return 1 return n * factorial(n - 1) # recursive call

print(factorial(5)) # Output: 120 ```

Every recursive function needs: 1) A **base case** (to stop), and 2) A **recursive case** (to reduce the problem). Without a base case, you get infinite recursion and a stack overflow.

Keep exploring

Related AI answers

View category
ScienceGPT-4o

What is quantum entanglement in simple terms?

Quantum entanglement is when two particles become correlated so that measuring one instantly determines the state of the other — no matter how far apart they are. **Simple analogy...

634
10,200
GeneralGPT-4o

How does sleep affect memory and learning?

Sleep plays a critical role in **memory consolidation** — the process of moving information from short-term to long-term memory. **During sleep:** - **Slow-wave (deep) sleep:** Th...

423
7,400
FinanceGPT-4o

What is the difference between a Roth IRA and a Traditional IRA?

Both are individual retirement accounts with tax advantages, but the timing of the tax break differs: **Traditional IRA:** - Contributions may be **tax-deductible** (reduces taxab...

412
7,800
CodingClaude 3.7

What is Big O notation? Explain with examples.

Big O notation describes how an algorithm's time or space requirements grow as input size (n) grows. It gives an upper bound on complexity. **Common complexities (best → worst):**...

401
6,700
CodingGemini 1.5

Explain SQL JOINs with a clear example

SQL JOINs combine rows from two tables based on a related column. Given: **users** (id, name) and **orders** (id, user_id, product) **INNER JOIN** — only rows that match in both ...

312
5,800
MathGPT-4o

What is a derivative in calculus? Explain intuitively.

A derivative measures the **instantaneous rate of change** of a function — how fast the output is changing at a specific point. **Intuition:** Imagine driving a car. Your position...

312
4,900