我正在尝试编写代码以生成一系列响应:如果用户输入1个数字,多个数字或一个字符串来生成斐波那契数字列表。代码如下:
def fib (a, b):
return a + b
number = int(input("Please write how many Fibonacci numbers you wish to have generated: "))
fibonacci_list = []
for n in range(number):
if n in [0, 1]:
fibonacci_list += [1]
print("The first", number, "Fibonacci number is:", fibonacci_list)
elif:
fibonacci_list += [fib(fibonacci_list[n-2], fibonacci_list[n-1])]
print("The first", number, "Fibonacci numbers are:", fibonacci_list)
else:
print('Sorry could not recognise the input')
答案 0 :(得分:0)
您也应该为elif
写一个条件,例如:
elif n in [1,2]:
在您的情况下,我将以这种方式编写代码:
def fib (a, b):
return a + b
try:
number = int(input("Please write how many Fibonacci numbers you wish to have generated: "))
fibonacci_list = []
for n in range(number):
if n in [0, 1]:
fibonacci_list += [1]
print("The first", number, "Fibonacci number is:", fibonacci_list)
else:
fibonacci_list += [fib(fibonacci_list[n-2], fibonacci_list[n-1])]
print("The first", number, "Fibonacci numbers are:", fibonacci_list)
except:
print('Sorry could not recognise the input')
答案 1 :(得分:0)
缺少精灵的条件。
答案 2 :(得分:0)
正如其他人所说,您错过了elif
中的条件,但是我强烈建议您在这种情况下使用sets
if n in {0,1}:
...
elif n in {1,2}:
...
sets
比列表具有更好的查找时间。另外,this is what they were meant for。
基本用途包括成员资格测试和消除重复条目。