1

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.

2 Answers 2

4

In the original code

    if len(words) == 0:
        continue
    if words[0] != 'From':
        continue

You reach continue in either case. Therefore the single line version should be

if len(words) == 0 or words[0] != 'From':
                #  ^ or, not and
    continue

If you need to use and, more refactoring is needed, switching the print and (now-implicit) continue and reversing the tests:

if len(words) > 0 and words[0] == 'From':
    print words[2]
Sign up to request clarification or add additional context in comments.

1 Comment

works great but I am instructed to use a and operator unless it's a book typo
2
fhand = open('mbox-short.txt')
for line in fhand:
    words = line.split()
    print 'Debug:', words
    if len(words) == 0 or words[0] != 'From':
        continue
    print words[2]

Change and to or.

1 Comment

works great but I am instructed to use a and operator unless it is a typo in the book

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.