7

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?

5 Answers 5

12

Use while loop:

 while True:

      if condition1:
            statements
      elif condition2:
            statements
      ...
      else:
            statements
Sign up to request clarification or add additional context in comments.

Comments

6
while True:
    # do stuff forever

Comments

1

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

1 Comment

Beware that there is no fall-through in if/elif/else like there would be in switch
1

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

2 Comments

This looks useful for infinite generator expressions like ('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.
@hobs To achieve that, you would use itertools.repeat('CONSTANT').
0

You can use

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

or

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

4 Comments

Normally it's more implicit to use the boolean 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?).
It is true, and using the boolean is (probably) the blessed way. That is just another example of achieving the same thing. var can change, but that is also up to the developer to not change it if she chooses to go that way. ;-)
But why have 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.
@Ben: We could go even further, and say while 1, which is tantamount to while True. But that's quite besides the point! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.