[Tutor] cases with single if and an else clause

Alan Gauld alan.gauld at yahoo.co.uk
Wed Oct 6 19:15:26 EDT 2021


On 06/10/2021 23:23, Manprit Singh wrote:

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

> My Next question is, in this particular scenario, where keeping the
> variable lst (which contains grade Characters and marks limits) as global
> and passing it as an argument to the function grades. So when this function
> is called, a copy of lst is created and it is destroyed upon exit from
> function.

Nope. When you pass the list to the function you pass a reference to it.
There is no copy made. The original list is still there in its global
space and the function parameter refers out to it.

> As the variable lst serves no other purpose, why not keep this lst as a
> local variable inside the function grades.

If you are sure that you won't want to refer to the list anywhere else
that would be fine. But what if you want to write some reports that map
grades to scores? You need to duplicate the data and then have a
maintenance headache.

Also what if you want to use the grades() function in anther program
that uses a different set of grades:

lst2 = [('fail':5),('pass',7)('credit":10)]

[ These were actually the scores used on my practical exams
during my apprenticeship. Theory exams used the more usual
A-F grades but practicals had this simpler fail/pass/credit
scheme based on the number of successful tasks out of 10.]

By keeping it as a parameter you have more options for reuse.

Of course you could make a default value for the glist parameter
and if it's None use your default set of values inside the function.
Best of both worlds? But you would need to make glist the second
parameter...

def grades(score,glist=None):
    if glist is None:
       glist = {("F",60),....]
    if score <...
etc

-- 
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