
Code
A Function That Calls Itself
A recursive function solves a problem by calling itself on a smaller version of the same problem. Every recursive function needs two parts:
- A base case: a version so small you can answer it directly.
- A recursive case: shrink the problem a little, call yourself, and use the answer.
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1) # recursive case
print(factorial(4)) # 4 * 3 * 2 * 1 = 24
Think of it as a promise: "Give me factorial(3) and I can make
factorial(4)." Python stacks up these promises until it reaches the
base case. Then it multiplies its way back out.
Pip tip: Each recursive call must move closer to the base case. Otherwise it calls itself forever.
Assignment
Use recursion (no loops) for both:
lantern_sum(n)returnsn + (n-1) + ... + 1. Forn <= 0it returns0.power(base, exp)returnsbaseraised toexp(a whole number>= 0) without using**orpow. Remember: anything to the power 0 is 1.
Use recursion (no loops) for both:
lantern_sum(n)returnsn + (n-1) + ... + 1. Forn <= 0it returns0.power(base, exp)returnsbaseraised toexp(a whole number>= 0) without using**orpow. Remember: anything to the power 0 is 1.
main.py Python sleeping
Press Run to try your code, then Check to test it.