继续得到同样的错误。 “语法无效”对Python编程非常新

时间:2014-01-30 07:52:03

标签: python syntax menu

以下是似乎有问题的代码:

elif answer == 2:
        students = ["Jonny Butler", "Harry Tennent", "Rashid Talha"]
        if raw_input("Which student are you looking for?") == students[0]:
            print "Jonny Butler," " Age: 15,"" Medical Condition: Asthma"
            elif raw_input("Which student are you looking for?") == students[1]:
                print "Harry Tennent, " "Age: 14, " "Medical Condition: None"
            elif raw_input("Which student are you looking for?") == students[2]:
                print "Rashid Talha, " "Age: 16, " "Medical Condition: None"
            else:
                print "Sorry, we don\'t appear to have that student on out database!"

错误一直说“第30行”的语法无效:

File "<stdin>", line 30 elif answer == 2: ^ SyntaxError: invalid syntax Unknown error

任何帮助都会很棒,我对Python很新。

2 个答案:

答案 0 :(得分:1)

elif之后的if语句没有正确缩进。也许您应该只询问用户输入一次:

elif answer == 2:
        students = ["Jonny Butler", "Harry Tennent", "Rashid Talha"]
        inp = raw_input("Which student are you looking for?")
        if inp == students[0]:
            print "Jonny Butler," " Age: 15,"" Medical Condition: Asthma"
        elif inp == students[1]:
            print "Harry Tennent, " "Age: 14, " "Medical Condition: None"
        elif inp == students[2]:
            print "Rashid Talha, " "Age: 16, " "Medical Condition: None"
        else:
            print "Sorry, we don\'t appear to have that student on out database!"

答案 1 :(得分:1)

如果使用字典,这会变得更有效:

elif answer == 2:
    students = {"Jonny Butler": {"Age": 15, "Condition": "Asthma"}, 
                "Harry Tennent": {"Age": 14, "Condition": None},
                "Rashid Talha": {"Age": 16, "Condition": None}}
    name = raw_input("Which student are you looking for?")
    if name in students:
        details = students[name]
        print "{0}, Age: {1[Age]}, Medical Condition: {1[Condition]}".format(name, details)
    else:
        print "Sorry, we don't appear to have that student on our database!"

重复代码的减少使得你犯错误的可能性大大降低(就像之前要求每个elif输入一样)。将数据(students)与显示(print)分开也意味着您可以更轻松地在其他地方重用数据。