我已经编程了一段时间(2年的工作+ 4.5年的学位+ 1年的大学预科课程),而且我从未使用过do-while循环而不是被迫参加编程入门课程.如果我从未遇到过如此根本的事情,我会越来越感觉我编程错了.
可能是因为我没有遇到正确的情况吗?
有哪些例子需要使用do-while而不是一段时间?
(我的学校教育几乎都是用C/C++编写的,我的工作是在C#中,所以如果有另一种语言绝对有意义,因为do-whiles的工作方式不同,那么这些问题并不适用.)
澄清......我知道a while和a 之间的区别do-while.在检查退出条件然后执行任务时.do-while执行任务然后检查退出条件.
所以,在Python中(虽然我认为它可以应用于许多语言),我经常发现自己有这样的事情:
the_input = raw_input("what to print?\n")
while the_input != "quit":
print the_input
the_input = raw_input("what to print?\n")
Run Code Online (Sandbox Code Playgroud)
也许我太挑剔了,但我不喜欢这条线有多the_input = raw_input("what to print?\n")重复.它降低了可维护性和组织性.但是我没有看到任何避免重复代码的变通方法而不会进一步恶化问题.在某些语言中,我可以这样写:
while ((the_input=raw_input("what to print?\n")) != "quit") {
print the_input
}
Run Code Online (Sandbox Code Playgroud)
这绝对不是 Pythonic,Python甚至不允许在循环条件AFAIK中进行赋值.
这个有效的代码修复了冗余,
while 1:
the_input = raw_input("what to print?\n")
if the_input == "quit":
break
print the_input
Run Code Online (Sandbox Code Playgroud)
但是也感觉不对.将while 1意味着这个循环将永远运行下去; 我正在使用一个循环,但给它一个假的条件并将真正的条件放入其中.
我太挑剔了吗?有一个更好的方法吗?也许有一些我不知道的为此设计的语言结构?