Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading