在Python中无限循环

时间:2012-01-03 14:46:53

标签: java python infinite-loop

我是Python的新手。实际上我使用Java实现了一些东西,如下所示。

 for(;;){
 switch(expression){
     case c1: statements

     case c2: statements


     default: statement
 }
}

如何在Python中实现它?

5 个答案:

答案 0 :(得分:12)

使用while循环:

 while True:

      if condition1:
            statements
      elif condition2:
            statements
      ...
      else:
            statements

答案 1 :(得分:6)

while True:
    # do stuff forever

答案 2 :(得分:1)

形式上,Python中没有switch语句;它是一系列嵌套的if-elif-else语句。

无限循环由while True语句完成。

所有在一起:

while True:
    if condition_1:
        condition_1_function
    elif condition_2:
        condition_2_function
    elif condition_3:
        condition_3_function
    else:  # Always executes like "default"
        condition_default_function

答案 3 :(得分:1)

如果您正在寻找一种在python中无限迭代的方法,您可以像for循环一样使用itertools.count()函数。 http://docs.python.org/py3k/library/itertools.html#itertools.count

答案 4 :(得分:0)

您可以使用

while True:
    if c1:
        statements
    elif c2:
        statements
    else:
        statements

var = 1
while var == 1:
    # do stuff