Python Forum
Problem with 'and' in 'if' statement - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Problem with 'and' in 'if' statement (/thread-21498.html)



Problem with 'and' in 'if' statement - CoderMan - Oct-02-2019

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?


RE: Problem with 'and' in 'if' statement - buran - Oct-02-2019

Yes, you are using and wrong
Look at https://docs.python.org/3/library/stdtypes.html#truth-value-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)



RE: Problem with 'and' in 'if' statement - CoderMan - Oct-06-2019

(Oct-02-2019, 10:20 AM)buran Wrote: Yes, you are using and wrong
Look at https://docs.python.org/3/library/stdtypes.html#truth-value-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?


RE: Problem with 'and' in 'if' statement - buran - Oct-06-2019

(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