2

I understand the code below works fine. Reading the while loop documentation in Python, they say that while expression should be True or False and that makes sense.

Now the readline() function returns string. So how this while loop works that way?

with open(datafile, "r") as f:
        line = f.readline();
        while line :
            print line
            line = f.readline()
            data.append(line)
        print line
    return data
MSaudi
  • 3,590
  • 2
  • 32
  • 58
  • Possible duplicate of [Truth value of a string in python](https://stackoverflow.com/questions/18491777/truth-value-of-a-string-in-python) – khelwood Aug 26 '18 at 06:52

2 Answers2

2

When used in a boolean context, many objects resolve to True or False, in this case that includes an empty string. Numeric zero, an empty tuple, list, set, and dictionary are also False.

A class can decide itself when/if an object is True or False by providing a __bool__ method (or __nonzero__ in Python 2). Although sometimes truth is not relevant for an object.

See also Defining "boolness" of a class in python

cdarke
  • 37,606
  • 5
  • 69
  • 77
0

A string in Python that is equal to "" evaluates to False, while any string that is not blank will evaluate to True.

#Evaluates to False
print(bool(""))

#Evaluates to True
print(bool("A String"))

In the loop you have specified, if there was a line that was successfully read, the string line will not be blank, and thus will evaluate to True. Once there is a line that didn't read in a string, the string line will be set to False and the loop should exit.

John Stark
  • 1,173
  • 1
  • 7
  • 20