0

For example, I have:

def run():
  x = input()
  switch (x):
    case 1:
      print "case 1"
    case 2:
      print "case 2"
      break;
    case 3:
      print "3"
    case (4,5):
      print "4"
      print "5"
      break;
    default:
      print "default"

It is just pseudocode on Python. I tried to rewrite this program using real Python syntax:

def run():
  x = input()
  if x == 1:
    print ("case 1")
  if x == 1 or x == 2:
    print ("case 2")
  else:
    if x == 3:
      print ("3")
    if x == 3 or x == 4 or x == 5:
      print ("4")
      print ("5")
    else:
      print ("default")

Looks very ugly. Can I do this in another way; for example, using dictionaries?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    [http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python](http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python) – logic Mar 21 '15 at 16:37

2 Answers2

0

Use elif function

if x == 1:
    print ("case 1")
elif x == 1 or x == 2:
    print ("case 2")
elif x == 3:
  print ("3")
elif x == 4 or x == 5:
  print ("4")
  print ("5")
else:
  print ("default")
0

You can use elif instead of writing

else: 
    if x == 3:

And in Python, if - elif is used as switch-case like below in the rewritten code of yours.

def run(): 
    x = input() 
if x == 1: 
    print ("case 1") 
elif x == 2: 
    print ("case 2") 
elif x == 3: 
    print ("3") 
elif x == 4 or x == 5: 
    print ("4") 
    print ("5") 
else: 
    print ("default")

And for dictionary use please check this link: Replacements for switch statement in Python

Community
  • 1
  • 1