// 打印小于 20 的数字 publicclassTest{ publicstaticvoidmain(String[] args){ int x = 10; do { System.out.print("value of x : " + x ); x++; System.out.print("\n"); } while(x 20); } }
事实上,在 2003 年时,有一个 PEP 提议给 Python 加上 do-while 语法支持:
PEP-315 Enhanced While Loop
该 PEP 提议增加一个可选的 do 子句,支持将 while 循环扩展成这样子:
do: while:
这不是简单地从其它语言翻译成 Python,它的 while 语句后保留了 Python 的缩进用法,并不会造成直译形式的突兀结果。
加上 while 循环本身已支持的可选的 else 子句,因此,while 完整的语法结构是这样的:
while_stmt : ["do"":" suite] "while" expression ":" suite ["else"":" suite]
(PS.在本系列的下一篇文章,我们将解释为什么 Python 要支持 while-else 语法)
也就是说,在保持原 while 循环语法不变的情况下,PEP-315 提议支持在 while 前面使用一个可选的 do 子句。
do 子句只会执行一遍,当它里面出现 break 时,则跳出整个 do-while 循环;当 do 子句中出现 continue 时,则跳出 do 子句,进到 while 的条件判断中。
有了 do 子句后,很容易就能实现 do {...} while (0) 的跳转控制效果。
但是,这个 PEP 遭到了一些核心开发者的反对。
反对的理由是,不需要引入新的关键字和语法,仅使用现有语法就能很好地实现同样的功能:
whileTrue: ifnot: break
Python 之父 Guido van Rossum 也持反对意见,他的原话是:
Please reject the PEP. More variations along these lines won't make the
language more elegant or easier to learn. They'd just save a few hasty
folks some typing while making others who have to read/maintain their code wonder what it means.