Python Forum

Full Version: Problem with 'and' in 'if' statement
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I'm trying to make a function that returns true if a list contains at least one of many predetermined letters in it. The code is as follows:

def check(x):
    if 'A' and 'B' and 'C' in x:
        return True
    elif 'A' and 'D' and 'G' in x:
        return True
    elif 'A' and 'E' and 'I' in x:
        return True
    elif 'I' and 'H' and 'G' in x:
        return True
    elif 'I' and 'F' and 'C' in x:
        return True
    elif 'D' and 'E' and 'F' in x:
        return True
    elif 'B' and 'E' and 'H' in x:
        return True
    else:
        return False
L = ['A', 'B', 'E', 'F']

print(check(L))
In this instance it should return false, since there are none of the series of three letters that I'm checking for, but it somehow returns true...

Am I using 'and' wrong?
Yes, you are using and wrong
Look at https://docs.python.org/3/library/stdtyp...ue-testing

'A' and 'B' and 'C' in x is same as True and True and 'C' in x
def check(iterable):
    sequences = ('ABC', 'ADG', 'AEI', 'IHG', 'IFC', 'DEF', 'BEH')
    return any(all(char in iterable for char in seq) for seq in sequences)
(Oct-02-2019, 10:20 AM)buran Wrote: [ -> ]Yes, you are using and wrong
Look at https://docs.python.org/3/library/stdtyp...ue-testing

'A' and 'B' and 'C' in x is same as True and True and 'C' in x
def check(iterable):
    sequences = ('ABC', 'ADG', 'AEI', 'IHG', 'IFC', 'DEF', 'BEH')
    return any(all(char in iterable for char in seq) for seq in sequences)

Oh I see. Thank you. So would it work if instead of A and B and C in x I write A in x and B in x and C in x?
(Oct-06-2019, 07:12 PM)CoderMan Wrote: [ -> ]So would it work if instead of A and B and C in x I write A in x and B in x and C in x?
yes it will work. But you will have a lot of repeating code. My example turns your 17 lines of code into 3 lines