How to Recurse in Python
How to Recurse in Python
Iteration is one of the ways to loop in python. However, recursion sometimes offers a more versatile way to loop through something.
Steps

Open a python editor. Many other python wikiHows, including Install Python, can show you how to do this.

Begin writing a function. This will require some knowledge of python functions. Our example function will be named sum_of and will take a_list as input.def sum_of(a_list):

Define the base case(s). Every recursive function must have at least one base case because later we are going to call the function within itself. To do this, you must ensure that eventually the function reaches a "stopping point" - the base case/cases. For this example there is one case: def sum_of(a_list): if len(a_list) == 0: return 0

Return the function itself. This will definitely seem counter-intuitive, so do this carefully. In this example, the sum_of function will be written, then how it works and how to make your own code will be described. def sum_of(a_list): if len(a_list) == 0: return 0 else: return a_list[0] + sum_of(a_list[1:]) Here's what really happens when we call this function with sample input sum_of([1,2,3]): >>>sum_of([1,2,3]) 6 The function runs through the first time and returns 1 + sum_of([2, 3]). It still needs to return a value since it has been called again, so it continues and we get 1 + 2 + sum_of([3]). Next, we get 1 + 2 + 3 + sum_of([]). That's a base case - sum_of([]) will always return 0. You're done! Python adds up these "promised" values and returns 6!

Test your function. As any good programmer will learn, you must test your function to make sure it works before moving on. Forgetting to test your functions before writing more code can cause bugs to crop up without you knowing what is wrong. Testing each function to make sure it does what it is supposed to is important. For this article's example sum_of function, we can input the empty list, or any list we want (that we can calculate mentally). It is recommended to write the function in file __main__, then run the code and call the function in the interactive python console. You could also use a few print statements at the end of the __main__ file. >>>sum_of([]) 0 >>>sum_of([1,2,3,4,3]) 13

What's your reaction?

Comments

https://sharpss.com/assets/images/user-avatar-s.jpg

0 comment

Write the first comment for this!