1

I have been struggling to troubleshoot a program, and I believe it comes down to this statement:

while line != '\n' or '':

I am reading a file using readline() and I'm struggling to fix the code in my function. For this while loop, I want it continue with these conditions: - line is not equal to '\n' OR - line is not equal to ''

Why doesn't this statement represent the above situation?

Jeffrey Y.
  • 95
  • 4
  • Canonical similar question: [Execute block if a variable is not one of some specific values](http://stackoverflow.com/questions/26337003/execute-block-if-a-variable-is-not-one-of-some-specific-values). – Veedrac Jan 03 '16 at 00:51
  • 1
    Do you just want read a file in Python? Why don't use `for` on the `file` object (actually, that called [`io.IOBase`](https://docs.python.org/3/library/io.html#i-o-base-classes)) or use [`file.readlines()`](https://docs.python.org/3/library/io.html#io.IOBase.readlines)? Relate: [Python: read file line by line into array](http://stackoverflow.com/questions/3277503/python-read-file-line-by-line-into-array). – Remi Guan Jan 03 '16 at 00:52

3 Answers3

3

You have to read

line != '\n' or ''

as

(line != '\n') or ''

The empty string evaluates to False in a boolean context, so your expression is equivalent to

line != '\n' or False

which is equivalent to

line != '\n'

You either need to write the expression like @houcros suggested, as

line != '\n' or line != ''

or as I would suggest, as

line not in ('\n', '')

which I think is easier to read. In your particular case, for this particular program, a simple

while line.strip()

would suffice, too - if line consists only of whitespace (check if that is what you actually want), line.strip() will be '', which evaluates to False as already mentioned.

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • `while line.strip()` is not the same as `while line != "\n"` – Padraic Cunningham Jan 03 '16 at 01:08
  • @PadraicCunningham nobody claimed that it is. I reminded the asker to double check if the `line.strip()` solution still does what he wants to do before using it, reminding him that `line.strip()` will return `''` if the line consists of whitespace only. – timgeb Jan 03 '16 at 10:49
2

While you say you want "line is not equal to '\n' OR line is not equal to ''", I think you really want "line is not equal to '\n' AND line is not equal to ''". Otherwise, your condition is trivially true (because line cannot both be equal to '\n' and be empty).

Therefore, I believe the condition you are looking for is:

while line != '\n' and line != '':

or equivalently,

while not (line == '\n' or line == ''):
Jonathan Callen
  • 11,301
  • 2
  • 23
  • 44
0

I believe it should be

while line != '\n' or line != '':
houcros
  • 1,000
  • 1
  • 14
  • 32