为什么当我正确缩进打印行时终端中出现语法错误消息,但当我缩进它时程序运行并打印输出 33 次?
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
>>>
一开始我用的是制表符,但是不一致,就用空格,算的很仔细。然后我尝试使用 Enter 键而不是 Return 键。然后我缩进打印语句和程序 运行,但输出很古怪:
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
这从第 0 行开始,每行每个数字打印大约 30 次。我想不出任何其他方法来尝试消除不允许我 运行 具有正确缩进的 print 语句的语法错误。如果这对有经验的程序员来说很明显,我深表歉意,但我们将不胜感激任何有用的提示。
当您使用交互式解释器时,您需要在缩进块的末尾包含一个空行,然后才能继续执行该程序。这只是交互式环境的一个怪癖,您的代码在 .py
文件中可以正常工作。
因此,您的会话应如下所示:
>>> 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)
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
>>>
一开始我用的是制表符,但是不一致,就用空格,算的很仔细。然后我尝试使用 Enter 键而不是 Return 键。然后我缩进打印语句和程序 运行,但输出很古怪:
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
这从第 0 行开始,每行每个数字打印大约 30 次。我想不出任何其他方法来尝试消除不允许我 运行 具有正确缩进的 print 语句的语法错误。如果这对有经验的程序员来说很明显,我深表歉意,但我们将不胜感激任何有用的提示。
当您使用交互式解释器时,您需要在缩进块的末尾包含一个空行,然后才能继续执行该程序。这只是交互式环境的一个怪癖,您的代码在 .py
文件中可以正常工作。
因此,您的会话应如下所示:
>>> 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)