0

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.

asked Feb 17, 2022 at 20:16

2 Answers 2

1

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]
answered Feb 17, 2022 at 20:21
Sign up to request clarification or add additional context in comments.

Comments

0

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()
answered Feb 17, 2022 at 20:27

3 Comments

You could explain that how you solved this problem instead of "how about this?".
Nice trick with ';' . I'll use for now on
I would not strictly consider using the semicolon to write one line if statements good practice.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.