gpt4 book ai didi

python - 为什么当我正确缩进打印行时终端中出现语法错误消息,但当我缩进它时程序运行并打印输出 33 次?

转载 作者:行者123 更新时间:2023-12-04 03:42:34 26 4
gpt4 key购买 nike

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 键。然后我缩进了 print 语句,程序运行了,但是输出很古怪:

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 语句的语法错误。如果这对有经验的程序员来说显而易见,我深表歉意,但我们将不胜感激任何有用的提示。

最佳答案

当您使用交互式解释器时,您需要在缩进 block 的末尾包含一个空行,然后才能继续执行该程序。这只是交互式环境的一个怪癖,您的代码可以在 .py 文件中正常工作。

因此,您的 session 应如下所示:

>>> 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)

关于python - 为什么当我正确缩进打印行时终端中出现语法错误消息,但当我缩进它时程序运行并打印输出 33 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65694330/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com