Search code examples
pythonpython-3.7

need help finding error on my python code


I am Writing a program to prompt for a score between 0.0 and 1.0. If the score is out of range print an error. If the score is between 0.0 and 1.0, print a grade using the following table:Score Grade >= 0.9 A>= 0.8 B>= 0.7 C>= 0.6 D< 0.6 F.

To give an example of what it should do at the end it is:

Enter score: 0.95, A Enter score: perfect, Invalid input Enter score: 10.0, Invalid input Enter score: 0.75, C Enter score: 0.5, F

This is the code I have now:

score = input("Enter Score: ")


try:
    score= float(score)
    if(score >= 0.0 and score <= 1.0):
        if (score>= 0.9):
            print("A")
        elif (score>= 0.8):
            print("B")
        elif(score>= 0.7):
            print("C")
        elif (score>= 0.6):
            print("D")
        elif (score < 0.6):
            print("F")
    else:
        print("Invalid input")

I cant seem to get it up and running. Any help would be appreciated.


Solution

  • Green-Avocado has a great answer. I would add a while loop to retry until the input is valid;

    # loop until complete
    while True:
        score = input("Enter Score: ")
    
        # let's try this 
        try:
            score = float(score)
            if score >= 0.0 and score <= 1.0:
                if score >= 0.9:
                    print("A")
                elif score >= 0.8:
                    print("B")
                elif score >= 0.7:
                    print("C")
                elif score >= 0.6:
                    print("D")
                elif score < 0.6:
                    print("F")
    
                # exit the loop on completion
                break
    
            # else raise an exception
            raise
    
        # if problem with float(score) or exception raised
        except:
            print("Invalid input")