Search code examples
pythonsyntax-error

Receiving errors with simple Python code, confused as to why. ActiveCode provides a whole other error


Here is the code to finding out a grade from a mark, pretty simple:

def grading(grade):
    n = (grade)
    
    if n >= 90:
        return "A"
    else:
        if n >= 80 and n < 90:
            return "B"
        else:
            if n >= 70 and n < 80:
                return "C"
            else:
                if n >= 60 and n < 70:
                    return "D"
                else:
                    return "F"
                 
m = float(input("What is your number grade?"))

print("Mark:", str(grade), "Grade:", grading(m)) 

I am getting a "SyntaxError: bad input on line 22" when running it

& the site I'm using (interactivepython.org) has an activecode function where it follows the code step by step and that produces the error of "IndentationError: unexpected indent (<string>, line 1)"


Solution

  • Won't fit in comments, but here is the if/elif construct.

    def grading(grade):
        if grade >= 90:
            return "A"
        elif grade >= 80:
            return "B"
        elif grade >= 70:
            return "C"
        elif grade >= 60:
            return "D"
        else:
            return "F"
    
    m = float(input("What is your number grade?"))
    
    print("Mark:", str(m), "Grade:", grading(m))
    

    Visualize it

    The decision process is the same, the second half of the conditions (e.g., if grade >= 80 and grade < 90 is unnecessary, because we've already guaranteed that grade < 90 by falling to this point in the decision tree: If grade is greater than or equal to 90, none of the elif blocks will execute. If it is less than 90, only one of the elif blocks will execute, so there is no need to test both bounds of the range, just check against the min.