I am going through chapter 8 of Python for Informatics and have been asked for an exercise to rewrite the following function:
fhand = open('mbox-short.txt')
count = 0
for line in fhand:
words = line.split()
#print 'Debug:', words
if len(words) == 0:
continue
if words[0] != 'From':
continue
print words[2]
I was asked to rewrite it using a single compound if statement, so I wrote the following:
fhand = open('mbox-short.txt')
#count = 0 <-- not even sure why this is in the orginal
for line in fhand:
words = line.split()
print 'Debug:', words
if len(words) == 0 and words[0] != 'From':
continue
print words[2]
The first function works just fine, but the second gives me the following error:
Traceback (most recent call last):
File "ch8.py", line 258, in <module>
print words[2]
IndexError: list index out of range
I do not understand why what I wrote is returning the error, as far as I can tell I am doing the same exact thing, but apparently I am wrong, I just don't understand why. Maybe there is a subtle issue that I am just not picking up on.
Thank you,
UPDATE
Instructions 'use a compound logical expression using the and logical operator with a single if statement.