AndyLee
AndyLee

Reputation: 31

Why a syntax error message in Terminal when I indent the print line correctly, yet the program runs and prints the output 33 times when I indent it?

fname = input('Enter the file name:')
Enter the file name:mbox-short.txt
>>> fhand = open(fname)
>>> count = 0
>>> for line in fhand:
...     if line.startswith('Subject:'):
...         count = count + 1
... print('There were', count, 'subject lines in', fname)
  File "<stdin>", line 4
    print('There were', count, 'subject lines in', fname)
    ^
SyntaxError: invalid syntax
>>> 

At first I was using tabs, but they were inconsistent, so I used spaces, counting very carefully. Then I tried using the Enter key instead of the Return key. Then I indented the print statement and the program ran, but the output was wacky:

There were 0 subject lines in mbox-short.txt
There were 0 subject lines in mbox-short.txt
There were 0 subject lines in mbox-short.txt....to 
There were 27 subject lines in mbox-short.txt
There were 27 subject lines in mbox-short.txt
There were 27 subject lines in mbox-short.txt

This started at line 0 and it printed each line with each number about 30 times. I can't think of anything else to try to get rid of the syntax error that won't let me run the print statement with the correct indentation. My apologies if this is obvious to experienced programmers but any helpful hint would be greatly appreciated.

Upvotes: 3

Views: 127

Answers (1)

MattDMo
MattDMo

Reputation: 102852

When you're working with the interactive interpreter, you need to include a blank line at the end of an indented block before continuing with the program. It's just a quirk of the interactive environment, your code would work fine in a .py file.

So, your session should look like this:

>>> fname = input('Enter the file name:')
Enter the file name:mbox-short.txt
>>> fhand = open(fname)
>>> count = 0
>>> for line in fhand:
...     if line.startswith('Subject:'):
...         count = count + 1
... 
>>> print('There were', count, 'subject lines in', fname)

Upvotes: 1

Related Questions