9 Years
Discussion Span
Last Post by sneekula

Probably only Guido knows for sure. This topic has come up a lot in the past. An if/elif chain is as concise as switch/case and allows for tests other than equality, so in some sense is more powerful. But it does not have the "semantic familiarity" of a switch statement, viz:

if x==1:
    do x == 1 things
elif x==2:
    do x == 2 things
elif x==3 and y==4: # try that in a case statement
    do x==2 && y==4 things
elif x==3 and y==0: # try that in a case statement
    do x==2 && y==0 things
elif x > 3:
    things to do when x > 3 # try that in a case statement
    do default things

what is the reason why Python doesn't have switch statement ?

Even in C the switch/case is not as efficient as multiple if/else and the cases are rather limited.

Actually, a dictionary makes an excellent replacement for a switch/case and is very high speed on the lookups:

# a dictionary switch/case like statement to replace
# multiple if/elif/else statements in Python

def switch_case(case):
    return "You entered " + {
    '1' : "one",
    '2' : "two",
    '3' : "three"
    }.get(case, "an out of range number")

num = raw_input("Input a number between 1 and 3: ")
print switch_case(num)
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.