斐波那契的Python代码

用户3822016

下面的代码工作正常,但有人可以解释一下for i in range(n)在我输入的不同值时,值怎么改变或如何添加的情况n

代码如下:

def fib():

    old = 0
    new = 1
    new_num = 1 #fibonacci number which will change
                #depending on the value of n.

    n = int(input("Please enter a number: "))
    for i in range(n):
        new_num = old + new
        new = old
        old = new_num
        new_num = new_num

    if n <= 0:
            print ("Please enter a number greater than 0.")
    elif n == 1:
            print ("The value is 1.")
    else:
            print ("The value is %s." % (new_num))

fib()

就像我提到的那样,我得到了正确的答案,但是我无法完全理解代码是如何工作的,并且更改了值,因为“ N”没有任何关联。

嗡嗡声

每次运行循环时,您都用刚创建的数字替换较旧的数字。n等于您输入的内容。假设您输入了4for循环将从0到3(4次)运行。首先,它是增加的价值old,并new创造new_num既然已经在该系列的下一个数字,它是那么覆盖的旧值old,并new以该系列中的最后两个值。它一直这样做直到循环结束。

当我= 0; 旧= 0; 新= 1; new_num = 1

当我= 1; 旧= 1; 新= 1; new_num = 2

当我= 2; 旧= 2; 新= 1; new_num = 3

当我= 3; 旧= 3; 新= 2; new_num = 5

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章