Why am I receiving a SyntaxError: invalid syntax regarding the use of an elif statement?

Why am I receiving a SyntaxError: invalid syntax regarding the use of an elif statement?

我正在尝试编写生成一系列响应的代码:如果用户输入 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')

你也应该为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')

您的 elif 中的条件缺失。

正如其他人所说,您在 elif 中遗漏了一个条件,但我强烈建议在这种情况下使用 sets

if n in {0,1}:
    ...
elif n in {1,2}:
   ...

sets 比列表有更好的查找时间。另外,this is what they were meant for

Basic uses include membership testing and eliminating duplicate entries.