recursion
Syntactically, recursion is the simple: it is a function that calls itself. e.g.:
def f(n):
...
f(n-1)
recursive function
def factorial(n):
if n == 1:
return 1 # base case
if n > 1:
return n * factorial(n - 1) # recursive case
note: the assignment of parameter
e.g. calculate the annaul rate in bank
def cal_rate(i, n):
if n == 0:
return 1
else:
# assign exactly how many parameters in function
return (i + 1) * cal_rate(i, n-1)
p = 1000
total_money = p * cal_rate(0.1, 5)
print(total_money)
1610.5100000000007
Process finished with exit code 0
If missing, error prompts:
return (i + 1) * cal_rate(n - 1)
TypeError: cal_rate() missing 1 required positional argument: ‘n’