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?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

for other beginners like me: running python with -t(or -tt) option will generate warnings(or errors) for inconsistent tab/space indentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.