user16728667
user16728667

Reputation:

While condition not breaking

Why while condition does not work for this case ?

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

On the comment line, i see that when i input 10 it should break on this case
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] 10 10 len(fbnc_list) == user / 10 == 10.
So _continue is set to False and while should stop. Not what it's happening.

Upvotes: 0

Views: 44

Answers (2)

Shawn Ramirez
Shawn Ramirez

Reputation: 833

how about this?

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

Upvotes: 0

Samwise
Samwise

Reputation: 71454

Setting _continue_ to False will stop the while loop at its next iteration, but it won't break out of the for loop.

If you want to immediately stop the loop, you'll need to unset _continue_ and immediately break the for loop:

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

Note that you don't need two loops in the first place -- a single for loop with as many iterations as you need additional items (i.e. the amount of desired numbers minus the two you started with) will suffice:

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]

Upvotes: 1

Related Questions