相关疑难解决方法(0)

在Python中模拟do-while循环?

我需要在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)

python while-loop do-while

731
推荐指数
13
解决办法
120万
查看次数

如何在Python中打破多个循环?

给出以下代码(不起作用):

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__

python break control-flow

440
推荐指数
15
解决办法
35万
查看次数

为什么python在for循环之后使用'else'?

我理解这个结构是如何工作的:

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编码器如何在他们的脑海中读取这个结构(或者如果你愿意的话,大声朗读).也许我错过了一些会让这些代码块更容易破译的东西?

python for-loop if-statement for-else

417
推荐指数
16
解决办法
14万
查看次数

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:

python

26
推荐指数
6
解决办法
3万
查看次数

在Python中命名循环

我最近读到了这个问题,它有一个关于在Java中标记循环的解决方案.

我想知道Python中是否存在这样的循环命名系统.我曾多次遇到过需要for从内for循环中突破外循环的情况.通常,我通过将内部循环放在一个返回(以及其他)布尔值的函数中来解决这个问题,该布尔值用作断开条件.但是标记循环的中断似乎要简单得多,我想尝试一下,如果python中存在这样的功能

有谁知道它是否存在?

python label for-loop break

15
推荐指数
3
解决办法
1万
查看次数