I've been trying to generate a Fibonacci sequence using Python 3. Since I'm totally new to programming I'm using basic tools. Lists in this case, as an exercise. The problem, I have, is to stop the sequence when I want it to stop.
For example,I need a Fibonacci up to 100 so I wrote this:
fib = [1,2]
n = 0
while max(fib) <= 100:
fib.append(fib[n]+fib[n+1])
n = n+1
print(fib)
print(max(fib))
print(n)
The print() statements are for my benefit only, so I would know what is going on.
In return I get:
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
144
9
So everything is working fine except I intended the sequenced to be finished before it passes 100. Why I have the 144 there then? What am I doing wrong?
fibis 89, so it's less than 100. because the condition is still satisfied at that point, it still generates one more.max(fib)withfib[-1]because thefiblist is always sorted und thus the maximum element is always the last.