Simple boolean inequality operators mistake

后端 未结 6 624
醉话见心
醉话见心 2020-12-12 01:54

Using inequality operators, I have to define a procedure weekend which takes a string as its input and returns the boolean True if it\'s \'Saturday

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 02:49

    Tip for the future: think through your code as if you were the computer in excruciating detail. For example, I would literally have this conversation with myself:

    Hmm, when day = 'Saturday', the code is returning False even though I think it shouldn't. Let's see what's going on line-by-line.

    def weekend(day):

    • Okay that seems good from now on I'll replace day with 'Saturday' anytime I see it...

    if day != 'Saturday' or day != 'Sunday':

    • Okay so I'll mentally translate this to if 'Saturday' != 'Saturday' or 'Saturday' != 'Sunday': .
    • Now I'll simplify it by evaluating the comparisons.
      • 'Saturday' != 'Saturday' becomes False
      • 'Saturday' != 'Sunday': becomes True
    • Plugging those in, I see that the if statement is saying if False or True, which is the same as if True. So that means that day = Saturday leads to a return value of False .

    Aha, so now I see what was wrong with the day = 'Saturday' case; the day != 'Sunday' condition meant that the if evaluated to True.

    So while the code below would return True for day = 'Saturday',

    def weekend(day):
        if day != 'Saturday':
            return False
        else:
            return True
    

    and this code would work for day = 'Sunday',

    def weekend(day):
        if day != 'Sunday':
            return False
        else:
            return True
    

    the two cannot be combined with an or.

    So try to talk to yourself like that in the future- it's super useful for debugging, especially when there is confusing boolean logic.

    (For the record, I think that return day.lower() in ['saturday','sunday'] is the best way to approach this.)

提交回复
热议问题