0

I was making a program for fibonacci series.

x=0
y=1
print (x)
print (y)
z = None
for z in range(1,100,x+y):
    z=x+y
    print(z)
    x = y
    y = z

The problem was that the output showed numbers more than 100. Here is a sample of the output

0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765

Why are there values greater than 100?

Note: this program was written in python 3.6

DavidG
  • 24,279
  • 14
  • 89
  • 82
  • 1
    not sure about the question, but here's some observations: `range(1,100,x+y)` is same as `range(1,100)` since default `step` value is `1`... that means the loop will iterate `99` times and you have 2 print stmts before the loop.. so total 101 lines in output.. – Sundeep Sep 03 '18 at 15:06
  • The step argument doesn't change throughout the for loop, so it will always step as one. –  Sep 03 '18 at 17:25

2 Answers2

0

The problem is that you run the loop 100 times rather than checking if the result is less than 100. The code is probably easier to read if you use a while loop rather than a for loop:

x=0
y=1
while True:
    fib = x + y
    if fib < 100:
        print (fib)
        x = y
        y = fib
    else:
        break
DavidG
  • 24,279
  • 14
  • 89
  • 82
-1

If you want it to stop at a given number you need an if statement, if not you it will run the fibonacci sequence 100 times

x=0
for number in range(1,100):
    x = number + x
    if x <= 100:
        print(x)
    else:
        break

Also you dont have to use step as it automatically increments by one for each loop

And the answer to your Q why are they more than hundred: because you run the fibonacci sequence 100 times, you dont stop it when it reaches 100.

Stanley
  • 2,434
  • 18
  • 28