Does python support switch or case statement in Python?If not what is the reason for the same?

Questions by Bessie   answers by Bessie

Showing Answers 1 - 20 of 20 Answers

Amit

  • Aug 6th, 2007
 

No. You can use multiple if-else. as there is no need for this.

  Was this answer useful?  Yes

Matt Brown

  • Jun 9th, 2011
 

You can use a dictionary to simulate the switch statement.


def doSomething():
    print "doSomething() called"

def doSomethingElse():
    print "doSomethingElse() called"

def doDefault():
    print "doDefault() called"


switch = {0:doSomething, 1:doSomethingElse}

switch[0]()
doSomething() called

switch.get(2, doDefault)()
doDefault() called

  Was this answer useful?  Yes

Geek4Geek

  • Jun 13th, 2011
 

No. Python does not have any switch or case statement. But it provides other ways of achieving multiway branching such as if-elif statements and dictionaries. 


Example 1: (Using if-elif-else)

if x == "String 1" :
#Perform action 1
elif x == "String 2" :
#Perform action 2
else :
#Perform action default


Example 2: (Using Dictionary)

answer = {
    1: "Monday",
    2: "Tuesday",
    3: "Wednessday",
    4: "Thursday",
    5: "Friday"
    }.get(n, "Not a working day") 


  Was this answer useful?  Yes

Surajano

  • Jun 18th, 2015
 

One to one Mapping can be done
here is my code:

Code
  1. def mySwitch(val):

  2.     return {

  3.         a: apple,

  4.         b: ball,

  5. ......

  6.     }.get(val, 9)

  Was this answer useful?  Yes

test

  • Jul 24th, 2015
 

There no switch case in Python.

  Was this answer useful?  Yes

No, Python does not support Switch statement, but we can implement Switch function and then use it. For example

def switch(input value ):
if value == some value:
take some operation
elif value == some value:
take some operation
else:
this is default option take some operation

so this way to achieve Switch statement

  Was this answer useful?  Yes

divyang bissa

  • Feb 27th, 2016
 

Actually there is no switch statement in the Python programming language but the is a similar construct that can do justice to switch that is the exception handling.using try and except1,except2,except3.... and so on

  Was this answer useful?  Yes

Amol

  • Jul 20th, 2017
 

Dictionary can be used as case/switch .

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions