Arnaud Bouffard
Arnaud Bouffard

Reputation: 3

Avoiding code repetition when returning a value only if True in Python

While coding a simple command-line tictactoe game to learn Python (here's a link to the entire script on repl.it), I was not happy with my game_over function, since a lot of code is repeated:

Edit: fixed the code by putting the [deck_is_full] if last instead of first

Edit 2: changed the code back to original for clarity

def game_over(deck):
    if deck_is_full(deck):
        return deck_is_full(deck)
    if three_in_line(deck, "X"):
        return three_in_line(deck, "X")
    if three_in_line(deck, "O"):
        return three_in_line(deck, "O")
    return False

Is there a pythonic, repetition-free way to code that? I have found this answer on SO, but it doesn't get rid of the repetition, just gets it into a one-liner.

Upvotes: 0

Views: 117

Answers (2)

superb rain
superb rain

Reputation: 5531

def game_over(deck):
    return deck_is_full(deck) or three_in_line(deck, "X") or three_in_line(deck, "O")

Edit: Had a look at your whole code and see that three_in_line returns true strings or the default None. So if you do need False here instead of None, then add it explicitly:

def game_over(deck):
    return deck_is_full(deck) or three_in_line(deck, "X") or three_in_line(deck, "O") or False

Edit 2: Hmm, just a note: If your functions had side effects, my version wouldn't be equivalent to yours, as I only call them once, not twice like you (when they return a true value). But as expected, and as they in my opinion should, they don't have side effects.

Upvotes: 5

tdelaney
tdelaney

Reputation: 77407

Since python 3.8 you can use the walrus operator to assign a variable in the if clause

def game_over(deck):
    if not (result:=deck_is_full(deck)):
        if not (result:=three_in_line(deck, "X")):
            if not (result:=three_in_line(deck, "O")):
                return False
    return result

Upvotes: 0

Related Questions