简体   繁体   中英

I keep getting a logic error trying to use the try-catch

I am learning python using a book, one of the excersises is; Exercise 3: Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error message. 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

I came up with the following;

inp = input('enter score: ')
try:
    float(inp >= 0.00) and float(inp <= 1.00)
    if inp >= 0.90:
        grade = 'A'
    elif inp >= 0.80:
        grade = 'B'
    elif inp >= 0.70:
        grade = 'C'
    elif inp >= 0.60:
        grade = 'D'
    elif inp < 0.60:
        grade = 'F'
    print('Grade: ',grade)
except: 
    print('bad score')

any input I input, regardless if it meets the conditions I set for the input or not comes out to the error message, "bad grade" Im not sure what I did wrong here honestly. Any help would be appreciated a lot.

The only code inside a try should be the code that can potentially raise an exception you want to handle. You should never use a bare except like this --always handle specific exceptions, or at the very least Exception .

The only operation that can throw an exception here is attempting to convert the user input (which is a string) to a numeric type, which will throw a ValueError . You can also raise a ValueError if the value isn't between 0 and 1:

try:
    score = float(input("enter score: "))
    if not (0.0 <= score <= 1.0):
        raise ValueError
except ValueError:
    print("please enter a decimal value between 0.0 and 1.0")

# Now do letter grade logic

With this try/except block, you can go one step further and wrap it in a loop that will keep asking the user for input until they enter a valid input:

while True:
    try:
        score = float(input("enter score: "))
        if not (0.0 <= score <= 1.0):
            raise ValueError
        break
    except ValueError:
        print("please enter a decimal value between 0.0 and 1.0")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM