I’m new to python and have been trying to create a simple grade calculator which tells the user what grade they’ve achieved based on their final score they’ve inputted.

def grades():
try:
    score = int(input("Please enter your score between 0 and 100:"))
    if score >= 90:
        print("Grade:A")
    elif score >= 80 :
        print("Grade:B")
    elif score >= 70:
        print("Grade:C")
    elif score >= 60:
        print("Grade:D")
    elif score >= 50:
        print("Grade:E")
    elif score < 50:
        print("Grade:F")
except score not in range (0,101) or ValueError:
    int(input("Incorrect value. Please enter your score between 0 and 100:"))

However when I try to run the program, it disregards the range and value error and gives it a grade anyway. Is there any way to rectify this, and if possible how could I make the program more efficient. As I said, I’m new to python, so any feedback would be useful.

Marcos246 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Simply assert that the input is in the determined range before checking through score ranges. Really, there is no need for a try/except statement.


def grades():
    while True:
        score = int(input(...))
        if 0 <= score <= 100:
            break
        # Invalid score
    # Check score ranges
    ...

Just for fun, let’s make it a Match Case statement:

def grades():
    while True:
        score = input("Please enter your score between 0 and 100: ")
        if score.isnumeric() and (score := int(score)) in range(0, 101):
            break
        else:
            print("Oops. sommthing went wrong")
    match score:
        case x if x in range(90,101) : print("Grade:A")
        case x if x in range(80, 90) : print("Grade:B")
        case x if x in range(70, 80) : print("Grade:C")
        case x if x in range(60, 70) : print("Grade:D")
        case x if x in range(50, 60) : print("Grade:E")
        case _ : print("Grade:F")

I have made changes to your code, please test to ensure it performs to expectations.

  1. I have added a while True loop, which attempts to validate the score to be between 0 - 100. If a non-integer value is entered it will hit the ValueError exception. This loop will only exit when a number within the range is entered.

  2. While some might argue that the if statement contains redundant comparator values, I prefer to be very specific. You can read more about interval comparators here.

  3. The if statement was also removed out of the try - except to make debugging easier. The idea is to have the least code possible in try - except so that when an exception triggers, it would be caused by the intended code.

  4. Lastly, you don’t want to ask for the user input inside the exception As the user might enter something which may cause another exception which will go uncaught.

def grades():

    while True:

        # Perform basic input validation.
        try:

            # Gets the user input.
            score = int(input("Please enter your score between 0 and 100: "))

            # Checks if the number entered is within 0 - 100. Note that range is non-inclusive for the stop. If it is within 0 - 100 break out of the while loop.
            if score in range(0, 101):
                break

        # If a non-integer is entered an exception will be thrown.
        except ValueError:
            print("Input entered is not a valid number")

    # Checking of scores using interval comparison
    if 90 <= score < 101:
        print("Grade:A")
    elif 80 <= score < 90:
        print("Grade:B")
    elif 70 <= score < 80:
        print("Grade:C")
    elif 60 <= score < 70:
        print("Grade:D")
    elif 50 <= score < 60:
        print("Grade:E")
    elif 0 <= score < 50:
        print("Grade:F")

1

Just do this:

def grades():
    try:
        score = int(input("Please enter your score between 0 and 100:"))
        if score > 100:
            while True:
                int(input("Incorrect value. Please enter your score between 0 and 100:"))
                if score <= 100:
                    pass
                else:
                    break
        if score >= 90:
            print("Grade:A")
        elif score >= 80 :
            print("Grade:B")
        elif score >= 70:
            print("Grade:C")
        elif score >= 60:
            print("Grade:D")
        elif score >= 50:
            print("Grade:E")
        elif score < 50:
            print("Grade:F")
    except:
        print("Oops. sommthing went wrong")

grades();

1

I made some corrections to your code. I added some comments to help explain what is going on. Let me know if this solution works for you:


def grades():
    while True:
        # Start a loop to ask for user input:
        score = int(input("Please enter your score between 0 and 100:"))
        # If not in range 1, 100, print error message
        if score in range(0, 101):
            break
        print('Incorrect value. Please enter your score between 0 and 100:')
         

    # calculate grade:
    if score >= 90:
        print("Grade:A")
    elif score >= 80:
        print("Grade:B")
    elif score >= 70:
        print("Grade:C")
    elif score >= 60:
        print("Grade:D")
    elif score >= 50:
        print("Grade:E")
    elif score < 50:
        print("Grade:F")


if __name__ == '__main__':
    grades()

3

Not the answer you’re looking for? Browse other questions tagged python or ask your own question.