Java Python中的无限for循环
我是Python新手。实际上,我使用Java实现了一些东西,如下所示Java Python中的无限for循环,java,python,infinite-loop,Java,Python,Infinite Loop,我是Python新手。实际上,我使用Java实现了一些东西,如下所示 for(;;){ switch(expression){ case c1: statements case c2: statements default: statement } } 如何在Python中实现这一点?使用while循环: while True: # do stuff forever while True: if condition1:
for(;;){
switch(expression){
case c1: statements
case c2: statements
default: statement
}
}
如何在Python中实现这一点?使用while循环:
while True:
# do stuff forever
while True:
if condition1:
statements
elif condition2:
statements
...
else:
statements
你可以用
while True:
if c1:
statements
elif c2:
statements
else:
statements
或
形式上,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
如果您正在寻找一种在python中无限迭代的方法,那么可以像for循环一样使用itertools.count()函数 如果我们谈论无限循环,通常使用布尔
True
而不是整数更为隐含。这样一来,意图就更清晰、更容易调试了(谁说var
的值可能不会随时间而改变?)。这是真的,使用布尔值(可能)是一种幸运的方式。这只是实现同样目标的另一个例子<代码>var可以更改,但如果开发人员选择这样做,也要由开发人员决定不更改它但为什么有var
?如果点的值总是等于1以创建一个无限循环,为什么不在1==1时说?既然这样做了,就不能只写而不是真的@Ben:我们可以更进一步,说而不是1
,这相当于而不是真的。但这完全不是重点!:)注意,if/elif/else
中没有像switch
中那样的漏洞。这对于无限的生成器表达式(如('CONSTANT'for i in itertools.count(0,0))
非常有用,可以作为预期生成器的函数的参数。您不必定义具有while True循环的单独函数。@hobs要实现这一点,您可以使用itertools.repeat('CONSTANT')
。
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