【发布时间】:2016-01-20 13:31:46
【问题描述】:
我知道要停止迭代 while 循环,您可以满足条件,也可以使用 break 命令。例如
apples = 10
while apples > 0:
apples -= 1
或
while True:
if apples == 0:
break
else:
apples -= 1
但这显然是一个非常基本的示例,我不确定在更大的代码示例中哪个更有用、更简单或更专业。我觉得这可能最终会更多地成为一种情况,但是,我似乎无法在谷歌上找到答案。谢谢。
编辑:
在过去的项目中使用第一个例子的例子:
finished_adding_object = False
while finished_adding_object == False:
print "System >>> Please enter new " + cls.__name__ + " name. If the user doesn't want to create a new " + cls.__name__ + ", please enter \"exit\"."
pending_new_object = raw_input("User >>> ")
while pending_new_object == "exit":
print "System >>> Please confirm, the user wishes to abandon creating a new " + cls.__name__ + "? (y/n)"
abandon_confirmation = raw_input("User >>> ")
if abandon_confirmation == "y":
pending_new_object = None
finished_adding_object = True
elif abandon_confirmation == "n":
pending_new_object = None
elif abandon_confirmation != "n" or "y": # User told if input is invalid.
print "System >>> " + abandon_confirmation + " is an invalid command."
【问题讨论】:
-
在如此多不同的情况下,有如此多不同的方法可以做到这一点,以至于不可能说哪一种是“最好的”。 “最佳”解决方案通常是最易读的,对特定情况有意义的解决方案。
标签: python while-loop conditional-statements break