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?
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
if/elif/else like there would be in switchIf 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
('CONSTANT' for i in itertools.count(0, 0)) as an argument to functions expecting a generator. You don't have to define a separate function that has the while True loop.itertools.repeat('CONSTANT').You can use
while True:
if c1:
statements
elif c2:
statements
else:
statements
or
var = 1
while var == 1:
# do stuff
True instead of an integer if we're talking infinite loops. This way, the intent is clearer and easier to debug (who's to say that the value of var may not change over time?).var can change, but that is also up to the developer to not change it if she chooses to go that way. ;-)var at all? If the point is to have a value that is always equal to 1 to create an infinite loop, why not just say while 1 == 1? And having done that, it's absurd not to just write while True.while 1, which is tantamount to while True. But that's quite besides the point! :)