For Loops and Recursive Sequences
In this example, we use for loops to generate a recursively defined sequence. We will demonstrate this by using Python to generate the first 50 Fibonacci numbers. Recall that the first two Fibonacci numbers are a1=a2=1, and every subsequent number is defined by an=an-1 + an-2 . So we begin by importing our sympy package and start our list of numbers a=[1,1]. We will create the rest of the numbers using a for loop. This is different from list comprehension primarily because we will be not be creating a list, but adding new elements to our existing list. The steps we will take within our loop are the following:
1)Compute a(n-1) + a(n-2)
2) “Append” it to the end of the list (Python command append)
Both computations can be done in one line of code by asking Python to append to list a a[n-2]+a[n-1]. In order for this to work with our initial list, we want to start our loop with n=2 and end with n=49 (since a[49] is the 50th element counting from n=0). So our for loop in its entirety is:
for n in range(2,50):
a.append(a[n-2]+a[n-1])
NOTE that when we go to the next line after the colon, Python automatically indents. When we press Enter again, Python continues to indent, but we can backspace to the beginning of the line. This tells Python that the loop ends, and any remaining commands are to be executed AFTER the loop is complete (when n = 49 since the range command is from 2 INCLUSIVE to 50 EXCLUSIVE). Finally, we print our list with appropriate text description.