我是Python的新手。实际上我使用Java实现了一些东西,如下所示。
for(;;){
switch(expression){
case c1: statements
case c2: statements
default: statement
}
}
如何在Python中实现它?
答案 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