Fibonacci的Python代码

时间:2014-07-09 19:54:08

标签: loops python-3.x fibonacci

下面的代码工作正常但有些人可以解释我在句子之后发生的事情 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()

就像我提到的那样,我得到了正确的答案,但是我无法完全理解代码是如何工作的并且改变了值 SINCE&#34; N&#34;没有链接到任何东西。

4 个答案:

答案 0 :(得分:1)

听起来你可能已经习惯了来自C或其他具有类似结构的语言的循环。在Python中,for i in range(n):表示“为0n-1之间的数字列表中的每个值运行此块中的代码一次,并依次将i设置为每个数字” 。 (从技术上来说,在Python 3中,它不是一个列表,而是一个迭代器,它按顺序生成数字而不将它们存储在列表中,但在这种情况下,差异在于学术界。)

所以:

  1. ninput()函数的用户输入设置。
  2. n用作range()函数的参数,当然不会更改n的值(它只会创建n个数字的列表) 。然后for循环对列表中的每个数字执行一次。
  3. n用于确定if / elif / else语句中的输出,同样不会更改n的值。

答案 1 :(得分:0)

循环执行n次。每次循环执行时,它都会根据先前计算的值计算第i个值。它不会改变n,只需使用n作为其评估次数的指示。

答案 2 :(得分:0)

我为你评论了你的代码。在尝试理解您的代码之前,您应该100%知道的是斐波纳契数是在它之前的序列中两个数字的总和。

重要的是要知道,因为“新”和“旧”是占位符。

**另请注意:** N与某物相关联,即范围。 N决定您要确定的Fibonacci范围内的索引。

def fib():

new = 1
old = 0
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):  # This is where the value of N is used 
    new_num = new + old  # new_num is the fibonacchi number at index "i", so to get it add the two before us
    old = new  # Update the old place holder (which is what new was, as we're updating new next)
    new = new_num  # Update new to be what we just calculating, so we can use it on the next iteration
    new_num = new_num  # Does nothing. Remove this line

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

与往常一样,如有任何问题,请在下方添加评论!

答案 3 :(得分:0)

每次运行循环时,您都会将旧数字替换为刚刚创建的数字。 n等于您输入的内容。假设您输入了4。 for循环将从0到3(4次)运行。首先,它是添加oldnew的值来创建new_num,因为你在系列中有下一个数字,然后它会覆盖old的旧值和new到系列中的最后两个值。它一直这样做,直到循环结束。

  

当i = 0时; old = 0; new = 1; new_num = 1

     当p = 1时

; old = 1; new = 1; new_num = 2

     

当i = 2时; old = 2; new = 1; new_num = 3

     

当i = 3时; old = 3; new = 2; new_num = 5