Fib Generator answer; Can't pass arguments in a function if it's functioning as an iterable?

时间:2018-07-25 05:07:44

标签: python-3.x

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

3 个答案:

答案 0 :(得分:1)

Following program will help you to find the Fibonacci series. You dont need to have the extra for loop in their.

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)

Edit:

Problem with your code is that your going into Never ending loop in your function. Also, your iterating with generator with variable n which is undefined. Modified your code little bit. Please refer the code below.

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)

Hope it helps.

答案 1 :(得分:0)

这是一个相当愚蠢的问题,现在我几个小时后再看一次,但这是我的问题的答案。

  

“如果函数是可迭代的,则不能在函数中传递参数?”   当然可以!

如果可以将函数用作迭代函数,则没有理由没有带参数的函数 (尽管它们仍然是函数!)

NameError原因

那时NameError的原因很简单,就像Python所说的:'n' is not defined。怎么可能我不是最后写了print(fib_g(3))吗?问题是for循环在该行之前运行。 (我知道这是个严重的错误...)

能够通过运行外部打印语句来运行代码的动机

如果您希望某人能够轻松运行fib代码而不必找到确切的行来编辑代码,或者如果某人正在导入您的fib代码并且您不希望他们进行编辑直接使用它,如果可以在代码外部定义n将会很有用。在这种情况下,代码应如下所示:

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


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


fib_g_print(6)

答案 2 :(得分:0)

您应将有效参数传递给fib_g而不是n,后者是仅在fib_g范围内使用的参数。另外,您应该初始化counter并在while循环内递增它:

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

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

这将输出:

0
1
1
2
3
5
8
13
21
34