Python 中的无限 for 循环

发布于 2024-12-24 20:57:47 字数 206 浏览 1 评论 0原文

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

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

     case c2: statements


     default: statement
 }
}

我如何在 Python 中实现这个?

I'm new to Python. Actually I implemented something using Java as shown below.

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

     case c2: statements


     default: statement
 }
}

How do I implement this in Python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

画尸师 2024-12-31 20:57:48

您可以使用

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

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

You can use

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

or

var = 1
while var == 1:
    # do stuff
も让我眼熟你 2024-12-31 20:57:47

使用 while 循环:

 while True:

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

Use while loop:

 while True:

      if condition1:
            statements
      elif condition2:
            statements
      ...
      else:
            statements
花伊自在美 2024-12-31 20:57:47
while True:
    # do stuff forever
while True:
    # do stuff forever
陈独秀 2024-12-31 20:57:47

正式来说,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

Formally, there's no switch statement in Python; it's a series of nested if-elif-else statements.

Infinite loops are accomplished by the while True statement.

All together:

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
故事灯 2024-12-31 20:57:47

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

If you are looking for a way to iterate infinitely in python you can use the itertools.count() function like a for loop. http://docs.python.org/py3k/library/itertools.html#itertools.count

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文