htennent
htennent

Reputation: 21

Keep getting the same error. "Invalid syntax" Very new to programming Python

Here's the code that appears to have the problem:

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!"

The error keeps saying that "line 30" has an invalid syntax:

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

any help would be great, I'm very new to Python.

Upvotes: 0

Views: 831

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122086

This becomes much more efficient if you use a dictionary:

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!"

The reduction in repeated code makes it much less likely you will make a mistake (like the previous asking for input on every elif). Separating the data (students) from the display (print) also means you can reuse the data elsewhere more easily.

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251031

The elif statements after the if are not indented properly. And probably you should ask for the user input only once:

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!"

Upvotes: 1

Related Questions