The program reads marks out of 100 and prints a grade: A for 90 and above, B for 80 to 89, C for 70 to 79, D for 60 to 69 and F below 60. Marks outside 0 to 100 are rejected.
The program
marks = float(input("Enter marks (0-100): ")) if not 0 <= marks <= 100: print("Invalid marks: enter a number from 0 to 100.") else: if marks >= 90: grade = "A" elif marks >= 80: grade = "B" elif marks >= 70: grade = "C" elif marks >= 60: grade = "D" else: grade = "F" print(f"Marks: {marks:g}, grade: {grade}")
Typed in this example: 84.5. Press Run to type your own.
Enter marks (0-100): 84.5 Marks: 84.5, grade: B
How it works
0 <= marks <= 100is a chained comparison: it means0 <= marks and marks <= 100.notturns it round, so the first branch runs for invalid marks.- The order of the checks matters. Python stops at the first condition that is true, so 84.5 fails
>= 90and then matches>= 80. The program never needs to checkmarks < 90. - If the checks were in the opposite order (
>= 60first), every mark of 60 or more would get a D. :gprints 84.5 as84.5and 90.0 as90.
Schools use different grade boundaries. To use your own, change the numbers in the conditions.
Grading a whole class
Put the rules in a function and call it for each student:
def grade_for(marks): if not 0 <= marks <= 100: return "invalid" if marks >= 90: return "A" if marks >= 80: return "B" if marks >= 70: return "C" if marks >= 60: return "D" return "F" results = {"Ada": 92, "Linus": 78, "Grace": 100, "Alan": 59.5, "Hedy": 60, "Margaret": 105} for name, marks in results.items(): print(f"{name:<9} {marks:>5} {grade_for(marks)}")
Ada 92 A Linus 78 C Grace 100 A Alan 59.5 F Hedy 60 D Margaret 105 invalid
Inside a function, each return ends the function, so plain if statements work here in the same way as elif. The test data includes the edge cases: exactly 100, exactly 60, just below 60, and a value above 100.