SunFounder ESP32 Starter Kit
Here, we have called the function with multiple arguments. These arguments are packed into a tuple before being
passed into the function.
Inside the function, we use a for loop to retrieve all the arguments.
Recursion
In Python, we know that a function can call other functions. It is even possible for the function to call itself. These
types of construct are termed as recursive functions.
This has the benefit of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never
terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion
can be a very efficient and mathematically-elegant approach to programming.
def rec_func(i):
if(i > 0):
result = i + rec_func(i - 1)
print(result)
else:
result = 0
return result
rec_func(6)
>>> %Run -c $EDITOR_CONTENT
1
3
6
10
15
21
In this example, rec_func() is a function that we have defined to call itself (“recursion”). We use the i variable as the
data, and it will decrement (-1) every time we recurse. When the condition is not greater than 0 (that is, 0), the recursion
ends.
For new developers, it may take some time to determine how it works, and the best way to test it is to test and modify
it.
Advantages of Recursion
• Recursive functions make the code look clean and elegant.
• A complex task can be broken down into simpler sub-problems using recursion.
• Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
• Sometimes the logic behind recursion is hard to follow through.
• Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
• Recursive functions are hard to debug.
3.6. 1.6 (Optional) MicroPython Basic Syntax 297