python中斐波那契函数,关于Python函数教程中的斐波那契序列示例

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)?

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值