CP104: Notes - Decision Problems

Here are a few problems that we often see with decision structures. Some of them apply to loop conditions as well:

Unnecessary else


if x > 0:
    y = True
else:
    y = y

  

As noted earlier, an if may stand alone - it does not require any elifs or an else. Anytime you assign a variable to itself you have to ask yourself, What is the point?


Unnecessary elif

    
if x == 0:
    z = True
elif x != 0:
    z = False

  

If there are only two possible conditions that can occur, chose one to explicitly check and leave the second to an else.


Misuse of and / or:

    
if x < 0 and x > 0:
    print('x is not equal to 0.')
else:
    print('x is equal to 0.')

  

The first condition can never be true - x cannot be both greater than 0 and less than 0 simultaneously. The condition should use an or instead. Think carefully of how you would state this logic in English before attempting to translate it to Python. (Of course, comparing x to 0 would be easiest!)


Incomplete Conditions

    
if course_code == 'CP' or 'PC':
    ....

  

No matter what the value of course_code, this condition will always be True. The string 'PC' is not actually compared to anything, and to Python the condition after the or is treated as the question, Does the string 'PC' exist? The answer to that is, of course, True. As already noted, the boolean and and or operators must have complete conditions on either side in order to be evaluated correctly. Thus, the corrected code is:

    
if course_code == 'CP' or course_code == 'PC':
    ....