-1

I am starting to learn Python and writing a small script with the following logic and can understand the reason for the output or the results I am getting. I have following code:

    test = ['aa01', 'zz02', '01']
    for element in test:
        print(f'{element}')
        if 'aa' or 'zz' in element:
            print('Condition met')
        else:
            print('Condition not met')

I get following output:

aa01
Condition met
zz02
Condition met
01
Condition met

With this line of code:

 if 'aa' or 'zz' in element:

I am expecting for each element in the list to look for a substring match (either 'aa' or 'zz') and then print if the condition is met. Based on the output I do not understand why the third element is matching this condition which does not have neither of the substring.

If I execute following code:

'zz' in 'aa01'
 False

and following code:

'zz' or 'aa' in 'aa'
'zz'

At this stage I am not how the substring matching is working, i.e. there is no 'zz' in 'aa'. Is it returning that 'zz' is not in 'aa'?

I also tried following code, which is also not giving me the desired result, well at least what I am expecting based on my understanding of Python so far.

test = ['aa01', 'zz02', '01']
for element in test:
    print(f'{element}')
    if 'aa' in element:
        print('Condition met')
    if 'zz' in element:
        print('Condition met')
    else:
        print('Condition not met')

This is the output i am getting:

aa01
Condition met
Condition not met
zz02
Condition met
01
Condition not met

So how is aa01 above showing Condition met and also at the same time showing Condition not met.

I cannot explain the behavior I am seeing. Would like someone to please explain this to me or point at some information on this.

Thanks a lot for help.

frank
  • 59
  • 2
  • 9

1 Answers1

0

That line isn't doing what you think it is doing.

When you write if this in that it checks to see if that contains this. If you just write if this: then it is just a truthy check which will always return True on strings except for the '' empty string.

So when you run if this or that in those:, what you are actually doing is asking 'if this' and 'if that in those' on the same line.

To make the line do what you expect it should be written like this:

if 'aa' in element or 'zz' in element:
    ... do something
Alexander
  • 16,091
  • 5
  • 13
  • 29