python如何重新运行程序?

时间:2015-04-16 21:46:34

标签: python loops

我写了一个函数来生成第一个n斐波纳契数。然而,它不断循环;我希望它停止并让用户选择计算斐波那契数的另一个序列。如果用户输入-1,则该流程应退出。

#fibonacci sequence : number is the sum of the previous row numbers
def fibonacci(n):
"""Return the first N numbers of the Fibonacci sequence."""
   a,b = 0,1
   for i in range(n):
       a,b = b,a+b
   return a

#main program
print("Fibonacci Sequence")
fib = int(input("Input a number to get its Fibonacci sequence: "))
while True:
    for i in range(fib):
        print(i, fibonacci(i))
        continue    
    else:
        fib == -1 #if user inputs -1 exit
        exit()

3 个答案:

答案 0 :(得分:1)

而不是:

fib = int(input("Input a number to get its Fibonacci sequence: "))
while True:
    for i in range(fib):
        print(i, fibonacci(i))
        continue
    else:
        fib == -1
        exit()

使用它:

while True:
    fib = int(input("Input a number to get its Fibonacci sequence: "))
    if fib == -1:
        break
    for i in range(fib):
        print(i, fibonacci(i))

答案 1 :(得分:0)

而不是while True:使用while fib != -1

fib = int(input("Enter a numher"))
while fib != -1:
    for i in range(fib):
        print(i, fibonacci(i))
    fib = int(input("Enter a numher"))

答案 2 :(得分:0)

print ("Fibonacci Sequence")
while True:
    fib =int(input("Input a number to get its Fibonacci sequence: "))
    if fib == -1:
        break
    for i in range(fib):
        print(i, fibonacci(i))
        continue