Regarding the Fibonacci Sequence example in Python's function tutorial

做~自己de王妃 提交于 2019-12-07 06:30:46

问题


This is what 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 employed, whereas mine proceeds 0, 1, 2, 4, 8, 16, 32...

I am currently learning programming (no prior computer science education), and it's clear that the problem is how I've defined my variables. What is the difference between separating the variables by commas and separating variables by a new line (assuming that is the issue)?


回答1:


This is a tuple assignment:

a, b = 0, 1

You can also think of it as

(a, b) = (0, 1)

A temporary tuple is created with the values 0, and 1 and then unpacked onto the variable a and b

This is also a tuple assignment

a, b = b, a+b

Again, you can think of it as

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

The temporary tuple is created from the values of b and a+b before either of them is updated. The assignment only happens after the temporary tuple is created.

By breaking it out to separate steps, you are changing the meaning of the code.

Lets see what happens here

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

Compare with

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



回答2:


There is only one difference:

In the first one, the assignment b = b+a is done before the modification of a. This is because, both the expression in RHS is evaluated first, before any assignment is done.

Whereas in the 2nd one, the 2nd assignment is done after the modification of a. That is why you are seeing wrong result.

So, in your code:

b = b + a

is actually:

b = b + b

because a has already been assigned the value of b.



来源:https://stackoverflow.com/questions/15515920/regarding-the-fibonacci-sequence-example-in-pythons-function-tutorial

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!