6

I know it's a basic question but please bear with me. Let's say if we have 4 strings below:

a = ''
b = 'apple'
c = 'orange'
d = 'banana'

So, normally if I want to check if any of the three string a b c is empty, I could use len() function.

if len(a) == 0 or len(b) == 0 or len(c) == 0:
    return True

But then I thought it is too troublesome to write like above if I have many strings. So, I used

if not a:
    return True

But, when i am checking for multiple strings b c d using the above method, it returns True and I am puzzled as non of the strings b c d where empty.

if not b or c or d:
    return True

What is going on?

Chris Aung
  • 9,152
  • 33
  • 82
  • 127
  • care to explain the reason for downvote? – Chris Aung May 07 '14 at 01:36
  • I suspect you may be expecting too much of the `or` operator. See http://stackoverflow.com/questions/15112125/if-x-or-y-or-z-blah. It's not quite clear whether this is a precedence confusion, a misunderstanding of what `or` really does, or something else. – user2357112 May 07 '14 at 01:37

2 Answers2

9

The problem lies with this line:

if not b or c or d:

You need to include the "not" condition for each string. So:

if not b or not c or not d:

You could also do it like this:

    return '' in [a, b, c, d]
James Scholes
  • 7,686
  • 3
  • 19
  • 20
3

The not operator has higher precedence than or.

return not b or not c or not d

should work.

peakxu
  • 6,667
  • 1
  • 28
  • 27