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.
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}