1

I'm following along with python official tutorial.
I've created a fibonacci function fib() as shown on the tutorial,
The output from the function given argument 1 was(to my surprise),
infinite trails of 0.

>>> def fib(n):
...     a, b = 0, 1
...     while a < n:
...         print a, 
...         a, b = b, a + b
... 
>>> fib(0)
>>> fib(1)
0 0 0 0 0 0 0 0 0 0 (...repeats infinitely, had to break out with ^+Z ...)

I've tried to reproduce the issue, but couldn't succeed.

>>> def fib(n):
...     a, b = 0, 1
...     while a < n:
...         print a,
...         a, b = b, a + b
... 
>>> fib(0)
>>> fib(1)
0
>>> fib(1)
0

Is this a known issue or perhaps some temporary glitch in the interpreter?

pradyunsg
  • 18,287
  • 11
  • 43
  • 96
Yeonho
  • 3,629
  • 4
  • 39
  • 61

1 Answers1

4

I can reproduce this:

>>> def fib(n):
...     a,b = 0,1
...     while a < n:
...         print a,
...         a,b = b, a+b
... 
>>> fib(5)
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 

How did I do it? The above code is really

def fib(n):
[tab]a,b = 0,1
[tab]while a < b:
[tab][4 spaces]print a,
[eight spaces]a,b = b, a+b

Mixing tabs and spaces confuses the interpreter about how it's supposed to parse the indentation. As a result, the a,b = b, a+b line isn't actually inside the while loop, even though it looks like it.

Yeonho
  • 3,629
  • 4
  • 39
  • 61
DSM
  • 342,061
  • 65
  • 592
  • 494
  • 1
    for other beginners like me: running python with `-t`(or `-tt`) option will generate warnings(or errors) for inconsistent tab/space indentation. – Yeonho Jan 28 '13 at 13:43