关于Python函数教程中的斐波那契序列示例 [英] Regarding the Fibonacci Sequence example in Python's function tutorial

查看:71
本文介绍了关于Python函数教程中的斐波那契序列示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是他们所具有的:

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

这就是我所拥有的:

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

第一个使用时返回正确的顺序,而我的返回0、1、2、4、8、16、32 ...

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

推荐答案

这是一个元组分配:

a, b = 0, 1

您也可以将其视为

(a, b) = (0, 1)

使用值01创建一个临时元组,然后将其解压缩到变量ab

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

这也是一个元组分配

a, b = b, a+b

同样,您可以将其视为

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

临时元组是在ba+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

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

这篇关于关于Python函数教程中的斐波那契序列示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆