-5 python syntax-error python-2.7 python-3.x
这段代码在编辑器中运行良好,但为什么我在尝试IDLE程序时遇到错误:
>>>i=1
while i<=5:
print(i)
i+=1
print("end")
Run Code Online (Sandbox Code Playgroud)
输出:SyntaxError:语法无效
预期产出:1 2 3 4 5结束
IDLE是一个python解释器,它逐个读取语句.你有3个陈述.
First: i = 1
Second: while i<=5:
print(i)
i+=1
Third: print("end")
Run Code Online (Sandbox Code Playgroud)
你必须将每个放在不同的行中.
>>> i = 1
>>> while i<=5:
print(i)
i+=1
else:
print("end")
1
2
3
4
5
end
>>>
Run Code Online (Sandbox Code Playgroud)
编辑:为此你可以使用其他与while.正确退出循环时将执行else块(即没有break语句.)