While循环问题。结果不是我预期的

我一般是Python和Stackoverflow的新手,如果我的格式很糟糕并且我的英语不好,那么抱歉。但是我对此代码有疑问。

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

这是代码的结果

Fibonacci sequence (2-10): 2
Fibonacci sequence up to 2: 0 1

这就是我所期望的结果。

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
评论
  • gomnis
    gomnis 回复

    看起来您只需要添加一个附加的验证步骤即可确保输入在所需范围内。这应该做。

    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