为什么会收到有关使用Elif语句的SyntaxError:无效语法?

时间:2018-08-02 12:11:04

标签: python if-statement conditional

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

3 个答案:

答案 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

  

基本用途包括成员资格测试和消除重复条目。