Skip to content Skip to sidebar Skip to footer

More Conditions In A Try/except Construct Python

I am trying to run a small program with try/except. It should return a mark between A and F for an input value (score) between 0 and 1. When I run it works as it should, i.e.for an

Solution 1:

Testing a float value with comparison operators doesn't raise an exception, so your exception handler is never reached. The if statement is simply false and that branch is not selected.

Either raise an exception manually (using raise ValueError('Value out of range') or handle that case explicitly with another print.

The only statement that you need to care about raising an exception is the float() function call. You should really limit your handler to that statement only, and only catch the ValueError exception that is raised when input is given that is not a float. You can combine the range check at that point to only have one print statement:

score = raw_input('Enter score: ')

try:
    score_float = float(score)
    ifnot (0.0 <= score_float <= 1.0):
        raise ValueError('Number out of range')
except ValueError:
    print'Error, please enter a valid number between 0.0 and 1.0'else:
    if score_float < 0.6:
        print'F'elif0.6 >= score_float < 0.7:
        print'D'elif score_float < 0.8:
        print'C'elif score_float < 0.9:
        print'B'else:
        print'A'

I simplified your tests; you don't need to test for a lower bound that earlier if and elif tests have already discounted.

You could use the bisect module to make translating the float value to a letter simpler:

importbisectnames= ['F', 'D', 'C', 'B', 'A']
values = [0.6, 0.7, 0.8, 0.9, float('inf')]
print names[bisect.bisect(values, score_float)]

Because 1.0 is included in the values that map to 'A' for bisection to work correctly, I used infinity to match the last entry.

Demo:

>>>import bisect>>>names = ['F', 'D', 'C', 'B', 'A']>>>values = [0.6, 0.7, 0.8, 0.9, float('inf')]>>>bisect.bisect(values, 0.72)
2
>>>names[bisect.bisect(values, 0.72)]
'C'
>>>bisect.bisect(values, 0.9)
4
>>>names[bisect.bisect(values, 0.9)]
'A'

Post a Comment for "More Conditions In A Try/except Construct Python"