Regarding an example of a Fibonacci sequence in a Python function tutorial

This they have:

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

This is what I have:

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

The first returns the correct sequence when used, while mine continues with 0, 1, 2, 4, 8, 16, 32 ...

I am currently studying programming (no prior education in computer science), and it is clear that the problem is how I defined my variables. What is the difference between splitting variables with commas and splitting variables on a new line (assuming this is a problem)?

+5
source share
2 answers

This is the purpose of the tuple:

a, b = 0, 1

You can also think of it as

(a, b) = (0, 1)

0 1, a b

a, b = b, a+b

,

(a, b) = (b, a+b)

b a+b , . .

, .

, .

a, b = 0, 1        # a=0 , b=1
a, b = b, a+b      # a=1 , b=1

a = 0              # a=0
b = 1              # a=0 , b=1
a = b              # a=1 , b=1
b = b+a            # a=1 , b=2 
+8

:

, b = b+a a. , RHS, .

, a. .

, :

b = b + a

:

b = b + b

a b.

+5

All Articles