Home > OS >  is there a simple way to test if any variable is " "?
is there a simple way to test if any variable is " "?

Time:10-24

I am learning python and I am almost done with making tick tack toe but the code for checking if the game is a tie seems more complicated then it needs to be. is there a way of simplifying this?

    if a1 != " " and a2 != " " and a3 != " " and b1 != " " and b2 != " " and b3 != " " and c1 != " " and c2 != " " and c3 != " ":
    board()
    print("its a tie!")
    quit()

CodePudding user response:

Instead of saving every single table field as it's own variable, I'd recommend saving them together under the same structure. My preference would be an array, but you could also use a dict. Here are two examples of how you would then check to see if all of the items are empty:

# list approach
table = [
    " "
] * 9 # length of board
if all(i != " " for i in table):
    print('Here if all elems equal " "')

# dict approach (if you need to keep track of each cell name, for example)
table = dict(
    a1= " ", 
    a2= " ", 
    a3= " ", 
    b1= " ",
    b2= " ",
    b3= " ",
    c1= " ",
    c2= " ",
    c3= " ",
)

if all(i != " " for i in table.values()):
    print('Here if all elems equal " "')

Edit: Changed to check != instead of ==

CodePudding user response:

If you add all the variables to a list you can check this with the any() function. Example:

listOfVariables = [a1, a2, a3, b1, b2, b3, c1, c2, c3]
if (any( " " == x for x in listOfVariables)) :
    #does stuff if any variable is " "

CodePudding user response:

If you insist on using a simple if statement the and ĺinkage of the boolean expressions is the way to do it.

However if you work with an array instead of single variables, e.g. fields = [a0, a1, a2, b0, b1, b2, c0, c1, c2]

you could use an loop condition:

should_break = True
for field in fields:
    if field == ' ':
         # any field is empty
         should_break = False
         break

if should_break:
    # end game here

or in short

if any( ' ' == field for field in fields):
    # end game here

CodePudding user response:

it looks like a few methods have been posted, so i throw this method into the ring.

this would work given the code:

a1, a2, a3 = " ", " ", " "
b1, b2, b3 = " ", " ", " "
c1, c2, c3 = " ", " ", " "

all_values = [
    a1, a2, a3,
    b1, b2, b3,
    c1, c2, c3
    ]

found = False
for i in all_values:
    if i != " ":
        found = True
        break

if found:
    print('something found')

CodePudding user response:

In your code, you check if all variables (a1, a2...) are different of " ", but you can also look if at least one of the variable is equal to " ".

a1, a2, a3 = " ", " ", "Y"
b1, b2, b3 = " ", "X", " "

#Create a list with all your variables
values = [a1, a2, a3, b1, b2, b3]

#Check if " " is in the list
if " " in values:
    board()
    print("its a tie!")
    quit()
  • Related