# others - еңЁpythonдёӯпјҢswitchиҜӯеҸҘзҡ„жӣҝжҚўе“Ғпјҹ

жҲ‘жғіеңЁpythonдёӯзј–еҶҷдёҖдёӘеҮҪж•°пјҢж №жҚ®иҫ“е…Ҙзҡ„еҖјпјҢиҜҘеҮҪж•°иҝ”еӣһдёҚеҗҢзҡ„еӣәе®ҡеҖјгҖӮ

еңЁе…¶е®ғиҜӯиЁҖдёӯпјҢжҲ‘еҸҜд»ҘдҪҝз”ЁswitchжҲ–caseиҜӯеҸҘпјҢPython дјјд№ҺжІЎжңүswitchиҜӯеҸҘпјҢеңЁиҝҷз§Қжғ…еҶөдёӢпјҢжҺЁиҚҗзҡ„Pythonи§ЈеҶіж–№жЎҲжҳҜд»Җд№Ҳпјҹ

ж—¶й—ҙ:

дҪ еҸҜд»Ҙз”Ёеӯ—е…ёпјҡ

``````
def f(x):

return {

\'a\': 1,

\'b\': 2,

}[x]

``````

еҰӮжһңдҪ жғіиҰҒй»ҳи®ӨеҖјпјҢеҸҜд»ҘдҪҝз”Ёеӯ—е…ё`get(key[, default])`ж–№жі•пјҡ

``````
def f(x):

return {

\'a\': 1,

\'b\': 2

``````

жҲ‘дёҖзӣҙе–ңж¬ўиҝҷж ·еҒҡ

``````
result = {

\'a\': lambda x: x * 5,

\'b\': lambda x: x + 7,

\'c\': lambda x: x - 2

}[value](x)

``````

жқҘиҮӘиҝҷйҮҢ

йҷӨдәҶеӯ—е…ёж–№жі•пјҲжҲ‘йқһеёёе–ңж¬ўпјүд№ӢеӨ–пјҢдҪ иҝҳеҸҜд»ҘдҪҝз”Ёif-elif-elseжқҘиҺ·еҫ—switch/case/defaultеҠҹиғҪпјҡ

``````
if x == \'a\':

# Do the thing

elif x == \'b\':

# Do the other thing

if x in \'bc\':

# Fall-through by not using elif, but now the default case includes case \'a\'!

elif x in \'xyz\':

# Do yet another thing

else:

# Do the default

``````

жҲ‘жңҖе–ңж¬ўзҡ„switch/caseзҡ„pythonй…Қж–№жҳҜпјҡ

``````
choices = {\'a\': 1, \'b\': 2}

result = choices.get(key, \'default\')

``````

е’Ң11иЎҢCд»Јз ҒжҜ”иҫғпјҡ

``````
// C Language version of a simple \'switch/case\'.

switch( key )

{

case \'a\' :

result = 1;

break;

case \'b\' :

result = 2;

break;

default :

result = -1;

}

``````

дҪ з”ҡиҮіеҸҜд»ҘйҖҡиҝҮдҪҝз”Ёе…ғз»„жқҘеҲҶй…ҚеӨҡдёӘеҸҳйҮҸпјҡ

``````
choices = {\'a\': (1, 2, 3), \'b\': (4, 5, 6)}

(result1, result2, result3) = choices.get(key, (\'default1\', \'default2\', \'default3\'))

``````

``````
class switch(object):

value = None

def __new__(class_, value):

class_.value = value

return True

def case(*args):

return any((arg == switch.value for arg in args))

``````

дҪҝз”Ёж–№жі•пјҡ

``````
while switch(n):

if case(0):

print"You typed zero."

break

if case(1, 4, 9):

print"n is a perfect square."

break

if case(2):

print"n is an even number."

if case(2, 3, 5, 7):

print"n is a prime number."

break

if case(6, 8):

print"n is an even number."

break

print"Only single-digit numbers are allowed."

break

``````

жөӢиҜ•пјҡ

``````
n = 2

#Result:

#n is an even number.

#n is a prime number.

n = 11

#Result:

#Only single-digit numbers are allowed.

``````

жҲ‘жңҖе–ңж¬ўзҡ„жҳҜrecipes пјҢдҪ е°Ҷйқһеёёе–ңж¬ўе®ғпјҢе®ғжҳҜжҲ‘и§үеҫ—е’Ңswitch caseиҜӯеҸҘжңҖжҺҘиҝ‘зҡ„дёҖдёӘпјҢзү№еҲ«жҳҜеңЁзү№жҖ§дёӯгҖӮ

``````
class switch(object):

def __init__(self, value):

self.value = value

self.fall = False

def __iter__(self):

"""Return the match method once, then stop"""

yield self.match

raise StopIteration

def match(self, *args):

"""Indicate whether or not to enter a case suite"""

if self.fall or not args:

return True

elif self.value in args: # changed for v1.5, see below

self.fall = True

return True

else:

return False

``````

иҝҷжҳҜдёҖдёӘдҫӢеӯҗпјҡ

``````
# The following example is pretty much the exact use-case of a dictionary,

# but is included for its simplicity. Note that you can include statements

# in each suite.

v = \'ten\'

for case in switch(v):

if case(\'one\'):

print 1

break

if case(\'two\'):

print 2

break

if case(\'ten\'):

print 10

break

if case(\'eleven\'):

print 11

break

if case(): # default, could also just omit condition or \'if True\'

print"something else!"

# No need to break here, it\'ll stop anyway

# break is used here to look as much like the real thing as possible, but

# elif is generally just as good and more concise.

# Empty suites are considered syntax errors, so intentional fall-throughs

# should contain \'pass\'

c = \'z\'

for case in switch(c):

if case(\'a\'): pass # only necessary if the rest of the suite is empty

if case(\'b\'): pass

# ...

if case(\'y\'): pass

if case(\'z\'):

print"c is lowercase!"

break

if case(\'A\'): pass

# ...

if case(\'Z\'):

print"c is uppercase!"

break

if case(): # default

print"I dunno what c was!"

# As suggested by Pierre Quentel, you can even expand upon the

# functionality of the classic \'case\' statement by matching multiple

# cases in a single shot. This greatly benefits operations such as the

# uppercase/lowercase example above:

import string

c = \'A\'

for case in switch(c):

if case(*string.lowercase): # note the * for unpacking as arguments

print"c is lowercase!"

break

if case(*string.uppercase):

print"c is uppercase!"

break

if case(\'!\', \'?\', \'.\'): # normal argument passing style also applies

print"c is a sentence terminator!"

break

if case(): # default

print"I dunno what c was!"

``````

``````
class Switch:

def __init__(self, value):

self.value = value

def __enter__(self):

return self

def __exit__(self, type, value, traceback):

return False # Allows a traceback to occur

def __call__(self, *values):

return self.value in values

from datetime import datetime

with Switch(datetime.today().weekday()) as case:

if case(0):

# Basic usage of switch

print("I hate mondays so much.")

# Note there is no break needed here

elif case(1,2):

# This switch also supports multiple conditions (in one line)

print("When is the weekend going to be here?")

elif case(3,4):

print("The weekend is near.")

else:

# Default would occur here

print("Let\'s go have fun!") # Didn\'t use case for example purposes

``````