Search code examples
pythonif-statementnestedparse-errorcomparison-operators

Python - Program That Prints Grade Using Nested If-Else Statements


I'm trying to create a program that prompts users to enter their grade, and then compares that value, x, in a series of nested If-Else statements:

x = int(input("What is your grade?"))
def grade(x):

if x >= 90:
        return "A"
    else:
        if x >= 80:
            return "B"
        else:
            if x >= 70:
                return "C"
            else:
                if x >= 60:
                    return "D"
                else:
                    return "F"

print( "Grade:", grade(x))

When I try to run this program, I get an error message:

ParseError: bad input on line 4

What's wrong with:

if x >= 90:

?

So far I haven't been able to get the dialogue box to show up asking for the user to enter their grade because of this error.

EDIT: After fixing indentation and using Elif

x = int(input("What is your grade?"))
def grade(x):

if x >= 90:
    return "A"

elif:
    x >= 80:
    return "B"
elif:
    x >= 70:
    return "C"
elif:
    x >= 60:
    return "D"
else:
    return "F"

print( "Grade:", grade(x))

Still gives me a syntax error:

SyntaxError: invalid syntax (<string>, line 7).

Solution

  • If you're using nested else-if, I suggest you use elif

    x = int(input("What is your grade?"))
    def grade(x):
        if x >= 90:
                return "A"
        elif x >= 80:
            return "B"
        elif x >= 70:
                return "C"
        elif x >= 60:
            return "D"
        else:
            return "F"
    
    print( "Grade:", grade(x))
    

    Input: What is your grade? 10

    Output: F

    And be careful about indented blocks!

    And here is syntax if you are unclear with it.

    if expression1:
       statements
    elif expression2:
       statements
    elif expression3:
       statements
    else:
       statements