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?

hobs
  • 18,473
  • 10
  • 83
  • 106
Kiran Bhat
  • 3,717
  • 4
  • 20
  • 18

5 Answers5

12

Use while loop:

 while True:

      if condition1:
            statements
      elif condition2:
            statements
      ...
      else:
            statements
soulcheck
  • 36,297
  • 6
  • 91
  • 90
6
while True:
    # do stuff forever
Rob Wouters
  • 15,797
  • 3
  • 42
  • 36
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
Makoto
  • 104,088
  • 27
  • 192
  • 230
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

tweirick
  • 171
  • 5
  • 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 Jul 12 '13 at 18:13
  • @hobs To achieve that, you would use `itertools.repeat('CONSTANT')`. – flornquake Aug 14 '13 at 17:29
0

You can use

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

or

var = 1
while var == 1:
    # do stuff
Milo Casagrande
  • 135
  • 1
  • 3
  • 11
  • 1
    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?). – Makoto Jan 03 '12 at 14:55
  • 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. ;-) – Milo Casagrande Jan 03 '12 at 15:24
  • 1
    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 Jan 03 '12 at 16:16
  • @Ben: We could go even *further*, and say `while 1`, which is tantamount to `while True`. But that's quite besides the point! :) – Makoto Jan 03 '12 at 17:59