Home>

I'm new to Python. I have a question about "War Game" in the book "Self-study Programmer".
# War Game code
Link content

There were the following functions in the code.

def __lt __ (self, c2):
    if self.value<c2.value:
        return True
    if self.value == c2.value:
        if self.suit<c2.suit:
            return True
        else:
            return False
    return False

I don't understand the role of return False on the last line. I tried to execute the code without the last line in the experiment, but it worked without any problems.

I would appreciate your reply.

  • Answer # 1

    Wouldn't it be convinced if you write as follows?

    def __lt __ (self, c2):
        if self.value<c2.value:
            return True
        elif self.value == c2.value:
            if self.suit<c2.suit:
                return True
            else:
                return False
        else:
            return False

    If you return the result, you exit the function, so you can omit the else clause.

      

    I tried to run the code without the last line in the experiment, but it worked fine.

    As already answered, None is returned, which can be determined as a false value.
    However,return Falseshould not be omitted semantically.

  • Answer # 2

    If there is no return in python, None will be returned, but it will be False at the time of evaluation, so the result will be the same.

  • Answer # 3

    In Python, the valueNoneis returned without writingreturn.

    And sinceNoneandFalseare both false as truth values ​​(reference), the result thrown intoifetc. will not change .

    Of course, if the processing is different depending on whether it isNoneorFalse, the result will change.