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

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

如果我在空闲状态下运行这段代码,结果是100500,但是在shell中有一个错误syntax error: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中必需的,但在从文件(或空闲)运行代码时则不需要。

关于python - Python Shell和IDLE之间的结果不同,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53550900/

10-10 21:39