Reputation: 1
I am new to Python and Stackoverflow in general, so sorry if my formatting sucks and I'm not good at English. But I have a problem with this code.
n = int(input("Fibonacci sequence (2-10): "))
a = 0
b = 1
sum = 0
count = 1
f = True
print("Fibonacci sequence up to {}: ".format(n), end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a = b
b = sum
sum = a + b
This is the result of the code
Fibonacci sequence (2-10): 2
Fibonacci sequence up to 2: 0 1
And this is the result that I expect.
Fibonacci sequence (2-10): 1
Invalid Number!
Fibonacci sequence (2-10): 15
Invalid Number!
Fibonacci sequence (2-10): 10
Fibonacci sequence up to 10: 0 1 1 2 3 5 8 13 21 34
Upvotes: 0
Views: 51
Reputation: 1631
Looks like you just need to add an additional validation step to make sure that the input is in the desired range. This should do it.
while True:
n = int(input("Fibonacci sequence (2-10): "))
if n<2 or n>10:
print("Invalid Number!")
else:
a = 0
b = 1
sum = 0
count = 1
f = True
print("Fibonacci sequence up to {}: ".format(n), end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a = b
b = sum
sum = a + b
break
Edit: To @Barmar's point, a loop on the outside would help avoid rerunning the code in case the input isn't within the desired range.
Upvotes: 2