Doomes
Doomes

Reputation: 25

If statement in function doesn´t return desired result

I want this function to check if there is " " in list test_board. But everytime it returns that what is after else statement. Why does it ?

test_board = ['#','X','O','X ','O',' ','O','X','O','X']

def full_board_check(board):
    for thing in board:
        if thing == " ":
            return False
        else:
            return True

When I call the funcition it returns True every time. No matter if there is " " in list or not. I want it to outuput False if any of the elements in the list is equal to " " which would mean that board isn´t full. And if there is no " " in the list it should return True because the board is full.

Upvotes: 1

Views: 39

Answers (1)

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181280

If you need to see the error in your logic is this:

def full_board_check(board):
    for thing in board:
        if thing == " ":
            return False
        else:
            # do nothing
            pass
    return True

The problem with your code is that when the first element is checked, you are returning True immediately. Not going through the whole list.

If you want a more pythonic way of doing what you are trying to, just do:

def full_board_check(board):
   return ' ' not in board

Upvotes: 1

Related Questions