首页 > 解决方案 > Fib Generator answer; Can't pass arguments in a function if it's functioning as an iterable?

问题描述

First off, sorry for the unclear question, I didn't know how else to address this. Here's a Fibonacci code I wrote using a generator, but somehow I'm getting a NameError: name 'n' is not defined.

def fib_g(n):
    a, b = 0, 1
    while counter <= n:
        yield a
        a, b = b, a + b


for i in fib_g(n):
    print(i)


print(fib_g(3))

so I changed things around and tried

def fib_g(n):
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b


counter = 0
for i in fib_g(n):
    if counter <= n:
        print(i)
        counter += 1

print(fib_g(3))

but I still get the same error:

Traceback (most recent call last):
  File "C:\Users\Desktop\fibonacci.py", line 20, in <module>
    for i in fib_g(n):
NameError: name 'n' is not defined

标签: python-3.x

解决方案


以下程序将帮助您找到斐波那契数列。你不需要在他们的里面有额外的 for 循环。

n = input('enter the length of the fib series? :')

num = int(n)
fib = []

#first two elements
i = 0
j = 1

count = 0

while count < num:
    fib.append(i)
    k = i + j
    i = j
    j = k

    count+=1

print(fib)

编辑:

您的代码的问题是您在函数中进入了永无止境的循环。此外,您使用未定义变量 n 的生成器进行迭代。稍微修改了你的代码。请参考下面的代码。

def fib_g(n):
    a, b = 0, 1
    x = 0
    while x < n:
        yield a
        a, b = b, a + b
        x+=1

for i in fib_g(10):
    print(i)

希望能帮助到你。


推荐阅读