Project 1 Notes on Creating a Program in Python to Generate the Fibonacci Sequence

Fibonacci Sequence

The Fibonacci Sequence is the series of numbers:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

The next number is found by adding up the two numbers before it.

Iteration

Iteration means executing the same block of code over and over, potentially many times. A programming structure that implements iteration is called a loop.

Flow of Execution

Python, in general, processes commands from top to bottom.

Indentation

All control structures in Python use indentation to define blocks.

Variable Assignment

Think of a variable as a name attached to a particular object. To create a variable, you just assign it a value and then start using it. Assignment is done with a single equals sign (=):

In [ ]:
t = 17 # This is read or interpreted as “t is assigned the value 17.”
print(t)
17
In [ ]:
t = 27 # if you change the value of n and use it again, the new value will be substituted instead.
print(t)
27
In [ ]:
s = 11
print(s)
s = 99
print(s)
11
99
In [ ]:
a = 0
b = 1
print(a)
0

Variable Type

In [ ]:
m = 77 # This assignment creates an integer object with the value 77.
type (m) 
Out[ ]:
int
In [ ]:
m1 = 77.7
type (m1)
Out[ ]:
float
In [ ]:
i = 1
while i < 6:
    print(i)
    i += 1
1
2
3
4
5

While Loops

  • i is initially 1.
  • Evaluate the while statement: If the while statement is true, the loop body executes. Inside the body, i is printed and then i is added by 1.
  • When the body of the loop has finished, program execution returns to the top of the loop, and then the while statement is evaluated again. If the while statement is still true, so the body executes again, and i is printed and then added by 1.
  • This continues until i becomes 5, which is less than 6. When i becomes 6, after the while statement is evaluated, it is false, and the loop terminates.
In [ ]:
n = 7
while n > 0:
    n -=1
    print(n)
6
5
4
3
2
1
0
In [ ]:
n = 7
while n > 0:
    print(n)
    n -= 1
7
6
5
4
3
2
1

Tuple Assignment

Tuples are defined by enclosing the elements in parentheses (( )) instead of square brackets ([ ]).

In [ ]:
a, b = 0, 1
print(a)
0
In [ ]:
type(a)
Out[ ]:
int
In [ ]:
type((a,b))
Out[ ]:
tuple
In [ ]:
a = 0
b = 1
while a<2:
    print(a)
    a, b = b, a+b
0
1
1
In [ ]:
# Fibonacci Sequencce
a = 0
b = 1
while a < 100:
    print(a)
    a, b = b, a+b
0
1
1
2
3
5
8
13
21
34
55
89
In [ ]:
a, b = 0, 1
while a < 100:
    print(a)
    a = b
    b = a+b
0
1
2
4
8
16
32
64
In [ ]:
a = 0
b = 1
while a < 1000000:
    print(a)
    a, b = b, a+b
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040