RECURSION

In [8]:
for i in range(5,10):
    print(i)
5
6
7
8
9

factorial(n) = 123...(n-1)*n

In [4]:
def factorial1(n):
    if n < 0:
        return None
    result = 1
    for i in range(2,n+1):
        result = result * i
    return result
In [7]:
factorial1(10)
Out[7]:
3628800
In [10]:
def factorial2(n):
    if n < 0:      # BASE CASE
        return None
    elif n <= 1:   # BASE CASE
        return 1
    else:
        return n*factorial2(n-1)   # RECURSIVE CASE
In [12]:
factorial2(10)
Out[12]:
3628800
In [13]:
def sum_list1(xs):
    result = 0
    for i in xs:
        result = result + i
    return result 
In [14]:
sum_list1([20,10,30])
Out[14]:
60
In [17]:
def sum_list2(xs):
    if xs == []:
        return 0
    else:
        return xs[0] + sum_list2(xs[1:])
In [18]:
sum_list2([20,10,30])
Out[18]:
60