Home > Mobile >  How can I check if a function returns a result in an "IF Else" statement
How can I check if a function returns a result in an "IF Else" statement

Time:12-16

def checkwin():
    if checkcolumn(board) or checkdiagonal(board) or checkrow(board):
        print(f"The winner is {winner}")

def checktie(board):
    # If no blank spaces("-") check it is a tie
    global gamerunning
    if "-" not in board and :
        printboard(board)
        print("It is a tie!")
        gamerunning = False

I'm trying to add a statement after and in the function checktie() to see if the statement "The winner is {winner}" is posted then we should ignore the checktie() function.

I tried inserting a boolean value to checkwin() but can't call it in the checktie() function

CodePudding user response:

The function needs to actually return a result:

def checkwin():
    return checkcolumn(board) or checkdiagonal(board) or checkrow(board)

Then you could do:

if "-" not in board and not checkwin():

However, you may want to rework your script because I don't know why checktie() would call checkwin() when whatever code is calling checktie() could simply call checkwin() itself. For example:

if checkwin():
    print(f"The winner is {winner}")
    gamerunning = False
elif checktie(my_board):  # This would need to return a boolean too.
    print("It is a tie!")
    gamerunning = False
else:
    # Continue game

CodePudding user response:

You can use another variable to determine the result.

has_won = False

def checkwin():
    global has_won
    if checkcolumn(board) or checkdiagonal(board) or checkrow(board):
        print(f"The winner is {winner}")
        has_won = True

def checktie(board):
    # If no blank spaces("-") and no winner is declared, check it is a tie
    global gamerunning
    if "-" not in board and not has_won:
        printboard(board)
        print("It is a tie!")
        gamerunning = False
  • Related