采用循环输入和输出

问题描述 投票:0回答:2

想想我试图制作一个程序,永远按顺序计算斐波那契数。我想让命令产生输出,并通过对其执行一些操作将输出视为输入。我该如何用 python 编写这样一个程序,如果它在某个点之后不会自动停止,我该如何让它停止?

所以我尝试过手动输入值,但不知道如何自动输入,因为我是新手。

recursion
2个回答
0
投票

每次递归的关键是需要退出条件。

因此,在递归方法中,您需要定义一个条件,在该条件之后您不想返回函数调用的结果,而是返回您想要的实际值。

举个例子:

def fibonacci(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)


n = 10
print(f"Fibonacci({n}) = {fibonacci(n)}")

0
投票

我建议看一下 生成器函数

举个例子,这里有一个生成器函数,它会永远产生偶数:

def gen_even():
    k = 0
    while True:
        yield k
        k += 2

然后你可以使用这个函数来获取一些偶数并对其进行运算:

for i, even_number in zip(range(10), gen_even()):
    square = even_number**2
    print(f'The {i}th even number is {even_number} and its square is {square}.')

输出:

The 0th even number is 0 and its square is 0.
The 1th even number is 2 and its square is 4.
The 2th even number is 4 and its square is 16.
The 3th even number is 6 and its square is 36.
The 4th even number is 8 and its square is 64.
The 5th even number is 10 and its square is 100.
The 6th even number is 12 and its square is 144.
The 7th even number is 14 and its square is 196.
The 8th even number is 16 and its square is 256.
The 9th even number is 18 and its square is 324.
© www.soinside.com 2019 - 2024. All rights reserved.