python-3.x - 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
解决方案
以下程序将帮助您找到斐波那契数列。你不需要在他们的里面有额外的 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)
希望能帮助到你。
推荐阅读
- flutter - 单选按钮选择不会在颤动的运行时出现
- php - 如何为 Firebase 中的每个令牌发送带有不同数据的推送?
- python - 从 Head 请求中捕获 IP 和端口
- css - 在css中将响应宽度分成4列
- javascript - 尚不可用的 setTimeout 访问元素
- unity3d - 如何防止同一预制件在 Unity 中连续生成两次
- jekyll - Jekyll 中的迭代 JSON 数据文件产生双重输出
- android - Android Studio Kotlin 活动在运行时不显示元素
- typescript - 输入“用户 | undefined' 不可分配给类型 'User'
- ecmascript-6 - undefined 不是 setInterval 附近的函数