[Tutor] cases with single if and an else clause

Alan Gauld alan.gauld at yahoo.co.uk
Wed Oct 6 07:30:36 EDT 2021


On 06/10/2021 12:04, Manprit Singh wrote:
> Dear Dennis Lee Bieber,
> 
> I  saw your explanation about my question :
> GRADES = [ (60, "F"),
>            (70, "D"),
>            (80, "C"),
>            (90, "B"),
>            (100, "A") ] #ordered list of breakpoints
> 
> These were the grades you have used, There is a problem, See if the marks
> are 60 That should not be classified as F . 

All you need to do is change the comparison from <= to <
(You also need to change the 100 to 101 for an "A" grade.)
Alternatively, change all the test values to the highest vale
for the grade: 59,69,...100 and keep the <= test

> The way i have implemented it given below:
> 
> def grades(glist, score):
>     if score < 0 or score > 100:
>         raise ValueError
>     for ch, rg in glist:
>         if score in rg:
>             return ch
> 
> lst = [("F", range(0, 60)),
>        ("D", range(60, 70)),
>        ("C", range(70, 80)),
>        ("B", range(80, 90)),
>        ("A", range(90, 101))]

But now there is much more work generating ranges and using
the in operation which implicitly loops over the values.
A simple comparison is much cheaper. Although your version
does exit as soon as it finds the correct range which will
compensate somewhat. But 5 comparisons should be cheaper than
an average of 3 'in' checks over 10 values(60 for the first!)
even though the 'in' is written in C.

> try:
>     marks= int(input("Enter marks"))
>     grade = grades(lst, marks)
> 
> except ValueError:
>     print("Invalid Value Entered")
> 
> else:
>     print(f'for {marks} marks the grade is {grade}')
> 
> Can I make such a  program without using range ?

Just change the comparison operator in Dennis' example.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list