user927584
user927584

Reputation: 395

Python grading program, need help w/ Ranging issue

Simple python program that takes the float value and returns the corresponding grade. I am having trouble ranging the grades so that right grade will be given to the marks. What is my problem here...? (I rather not use the 'and' conditions)

def grade(mark):
    if mark >= 80:
        letter = 'A'
    elif 65 >= mark <= 79:
        letter = 'B'
    elif 50 >= mark <= 64:
        letter = 'C'
    else:
        letter = 'F'
    return letter

Upvotes: 0

Views: 521

Answers (3)

Wooble
Wooble

Reputation: 89997

65 >= mark <= 79 is shorthand for:

65 >= mark and mark <= 79

All values less than 65 are also less than or equal to 79, but this won't find values actually in the range you're looking for.

You probably meant 65 <= mark <= 79

(As pointed out in the comments, if mark is a float even correcting this error will leave your function discontinuous since there are valid values, like 79.5, that you don't account for.)

Upvotes: 5

Martijn Pieters
Martijn Pieters

Reputation: 1123410

Return early for values over a limit, so there is no need to test for that upper limit again:

def grade(mark):
    if mark >= 80:
        return 'A'
    if mark >= 65:
        return 'B'
    if mark >= 50:
        return 'C'
    return 'F'

Your chained comparisons had the lower bound the wrong way around; you were testing if mark was smaller than 65; invert the tests:

elif 65 <= mark <= 79:
    letter = 'B'
elif 50 <= mark <= 64:
    letter = 'C'

The most efficient approach is to use bisect.bisect() and two lists:

import bisect

def grade(mark):
    grades = ['F', 'C', 'B', 'A']
    marks = [50, 65, 80]
    return grades[bisect.bisect(marks, mark)]

bisect.bisect() returns the index into which a mark would be inserted; 0-49 would be inserted at index 0 (translating to 'F'), 50-64 would be inserted at index 1 ('C'), etc.

Upvotes: 5

mauve
mauve

Reputation: 2763

I'm confused - you say you're using floats...what do you want to do with 79.5, for instance?

if mark >= 80:
    letter = 'A'
elif mark > = 70:
    letter = 'B'

etc....you only need to set the lower value, really.

Upvotes: 0

Related Questions