本文介绍了Python-Fibonacci函数的变量值声明之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的初学者.我正在研究一种实现斐波那契函数的类型,

I'm kind of beginner in python. I was looking at one the types to make a fibonacci function,

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

,我看到了a,b = b,a + b声明.因此,我认为a = b和b = a + b与a,b = a,b + a相同,因此我将其功能更改为:

and I saw the a,b=b,a+b declaration. So, I thought a=b and b=a+b were the same to a,b=a,b+a, so I changed the function for it to be like this:

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

,我认为这是正确的,但是当我执行程序时,得到了不同的输出.有人可以向我解释这两种声明之间的区别吗?

and I thought it would be right, but when I executed the program, I got a different output. Can someone explain to me the difference between those two types of declaration?

谢谢.

推荐答案

Python执行时

a,b = b, a+b

首先评估右侧,然后解压缩元组并将值分配给ab.请注意,右侧的a+b使用的是a值.

it evaluates the right-hand side first, then unpacks the tuple and assigns the values to a and b. Notice that a+b on the right-hand side is using the old values for a.

Python执行时

a=b
b=a+b

它计算b并将其值分配给a.然后,它计算a+b并将该值分配给b.现在请注意,a+b使用的是a new 值.

it evaluates b and assigns its value to a.Then it evaluates a+b and assigns that value to b. Notice now that a+b is using the new value for a.

这篇关于Python-Fibonacci函数的变量值声明之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:28