我需要在Python程序中模拟do-while循环.不幸的是,以下简单的代码不起作用:
list_of_ints = [ 1, 2, 3 ]
iterator = list_of_ints.__iter__()
element = None
while True:
if element:
print element
try:
element = iterator.next()
except StopIteration:
break
print "done"
Run Code Online (Sandbox Code Playgroud)
而不是"1,2,3,完成",它打印以下输出:
[stdout:]1
[stdout:]2
[stdout:]3
None['Traceback (most recent call last):
', ' File "test_python.py", line 8, in <module>
s = i.next()
', 'StopIteration
']
Run Code Online (Sandbox Code Playgroud)
我能做些什么来捕获'stop iteration'异常并正确地打破while循环?
以下将伪代码示为可能需要这样的事物的示例.
状态机:
s = ""
while True :
if state is STATE_CODE :
if "//" in s :
tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
state = …Run Code Online (Sandbox Code Playgroud) 给出以下代码(不起作用):
while True:
#snip: print out current state
while True:
ok = get_input("Is this ok? (y/n)")
if ok.lower() == "y": break 2 #this doesn't work :(
if ok.lower() == "n": break
#do more processing with menus and stuff
Run Code Online (Sandbox Code Playgroud)
有没有办法让这项工作?或者我是否已经做了一次检查以突破输入循环,然后另一个更有限的检查外部循环以在用户满意的情况下将所有内容分开?
Edit-FYI: get_input是我编写的一个简短函数,支持显示提示和默认值以及所有那些幻想和返回__CODE__
我理解这个结构是如何工作的:
for i in range(10):
print(i)
if i == 9:
print("Too big - I'm giving up!")
break;
else:
print("Completed successfully")
Run Code Online (Sandbox Code Playgroud)
但我不明白为什么else在这里用作关键字,因为它表明有问题的代码仅在for块未完成时运行,这与它的作用相反!无论我如何看待它,我的大脑都无法从for语句无缝地进展到else块.对我来说,continue或者continuewith更有意义(我正在努力训练自己阅读它).
我想知道Python编码器如何在他们的脑海中读取这个结构(或者如果你愿意的话,大声朗读).也许我错过了一些会让这些代码块更容易破译的东西?
for row in b:
for drug in drug_input:
for brand in brand_names[drug]:
Run Code Online (Sandbox Code Playgroud)
从第三个循环如何退出当前循环并转到下一个值for row in b:?
我最近读到了这个问题,它有一个关于在Java中标记循环的解决方案.
我想知道Python中是否存在这样的循环命名系统.我曾多次遇到过需要for从内for循环中突破外循环的情况.通常,我通过将内部循环放在一个返回(以及其他)布尔值的函数中来解决这个问题,该布尔值用作断开条件.但是标记循环的中断似乎要简单得多,我想尝试一下,如果python中存在这样的功能
有谁知道它是否存在?
python ×5
break ×2
for-loop ×2
control-flow ×1
do-while ×1
for-else ×1
if-statement ×1
label ×1
while-loop ×1