[Tutor] help with elif statements

Alan Gauld alan.gauld at freenet.co.uk
Thu Oct 13 10:49:21 CEST 2005

> below is my code and everytime I input a value of 16 or more it keeps
> returning sophomore. could anyone help me figure out what to change so
> that it won't return sophmore for things greater than or equal to 16?

This is one of the gotchas of if/elif chains and I discuss it in 
my branching topic in the tutorial.

Basically you have to sequence the tests to that you gradually 
filter out the ones you want.

> def getcredits(num):
>    if num < 7:
>        return 'Freshman'
>    elif num >= 7:
>        return 'Sophomore'

return exits the construct so you will always exit here or 
on the line above, you need to move this test to the bottom.
I'd suggest a sequence like:

>    if num < 7:
>    elif num <16:
>    elif num < 26:
>    elif num >= 16:
>    elif num >= 7:
>    else:
>        return 'Senior'

But mixing test types makes it really hard to do reliably. 
Its better to combine tests like this:

if num < 7: retiurn 'Freshman'
elif  7 <= num < 16: return  'Sophomore'
elif  16 <= num < 26: return 'Junior'
else: return 'Senior'

Which I think is what you are tring to do?

If thats too confusing you can use an explicit and test:

if num < 7: ...
elif (num >= 7) and (num <16): ...

The above is simply a shorthand way of writing the combined tests.


Alan G
Author of the learn to program web tutor

More information about the Tutor mailing list