Basic Recursion

Recursion is a functional way of doing loops. Using this approach, we can have a finer grain of control than for or while loops. Like any loop, infinite loops are possible so it is important that a break condition exist. Recursion is something that can be done in any programming language.
 avatar
c0dezer019
python
a year ago
456 B
8
Indexable
def recurse(arr: List[int], index=0):
    # break loop if our condition is met
    if arr[index] == 5:
        return True
    
    # if index + 1 is not equal to arr length, call self passing modified arguments and pre-increment index. This is cslled recursion.
    if index + 1 < len(arr):
        return recurse(arr, ++index)
        
    # will return False and break loop once index + 1 is equal to arr if primary condition isn't met.
    return False
Editor is loading...
Leave a Comment