Python shell 和 IDLE 之间的不同结果

Different results between Python shell and IDLE

下面的代码打印了从 1 到 1000 的 5 的倍数之和

s = 0
for i in range(1, 1001):
    if i % 5 == 0: s += i
print(s)

如果我运行这段代码在IDLE,结果是100500,但是在shell出现错误SyntaxError: invalid syntax,出来在 print。为什么 IDLE 和 shell 给出不同的结果?我的 Python 版本是 3.7.

在 Python shell(规范名称:REPL)中,您应该以空行结束缩进块,因此您应该 运行 在 REPL 中这样做:

s = 0
for i in range(1, 1001):
    if i % 5 == 0: s += i

print(s)

注意 print 之前的空行,这在 REPL 中是必需的,但当您 运行 来自文件(或 IDLE)的代码时则不需要。