虽然条件没有打破

While condition not breaking

为什么 while 条件不适用于这种情况?

 def Fibonacci():
    user = int( input("Type the length of Fibonacci numbers will be generated: ") )
    fbnc_list = [0, 1]
    
    _continue_ = True
    while _continue_:
      for n in range(0, user + 1):
        fbnc_list.append( fbnc_list[n] + fbnc_list[n + 1] )
        #print(fbnc_list, len(fbnc_list), user)
        if len(fbnc_list) == user: _continue_ = False

    return (fbnc_list)

Fibonacci()

在评论行上,我看到当我输入 10 时它应该在这种情况下中断
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] 10 10 len(fbnc_list) == user / 10 == 10.
所以 _continue 设置为 False 并且 while 应该停止。 不是它正在发生的事情。

_continue_ 设置为 False 将在下一次迭代时停止 while 循环,但不会跳出 for 循环。

如果你想立即停止循环,你需要取消设置_continue_ 立即中断for循环:

            if len(fbnc_list) >= user:
                _continue_ = False
                break

请注意,您一开始不需要两个循环——一个 for 循环,迭代次数与您需要的其他项目一样多(即所需数字的数量减去您开始时的两个数字) ) 就足够了:

def fibonacci(n):
    fibs = [0, 1]
    for _ in range(n - 2):
        fibs.append(fibs[-2] + fibs[-1])
    return fibs[:n]  # handles n < 2

print(fibonacci(int(input(
    "Type the number of Fibonacci numbers to generate: "
))))
Type the number of Fibonacci numbers to generate: 10
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

这个怎么样?

def Fibonacci():
    user = int( input("Type the length of Fibonacci numbers will be generated: ") )
    fbnc_list = [0, 1]
    
    _continue_ = True
    while _continue_:
      for n in range(0, user + 1):
        fbnc_list.append( fbnc_list[n] + fbnc_list[n + 1] )
        #print(fbnc_list, len(fbnc_list), user)
        if len(fbnc_list) == user: _continue_ = False;break

    return (fbnc_list)

Fibonacci()