Switch case syntax implementation in Python

Source: Internet
Author: User
Tags lowercase switch case in python

In other languages, the switch statement is probably like this

Switch (VAR)
{
Case VALUE1:DO_SOME_STUFF1 ();
Case VALUE2:DO_SOME_STUFF2 ();
...
Case VALUEN:DO_SOME_STUFFN ();
Default:do_default_stuff ();
}

Python itself does not have a switch statement, the solution has the following 3 kinds:

A. Use of dictionary

Values = {
VALUE1:DO_SOME_STUFF1,
VALUE2:DO_SOME_STUFF2,
...
VALUEN:DO_SOME_STUFFN,
}
Values.get (Var, do_default_stuff) ()

B. Using a lambda

result = {
' A ': Lambda x:x * 5,
' B ': Lambda x:x + 7,
' C ': Lambda x:x-2
}[value] (x)

C.brian Beck provides a class switch to implement switch functionality in other languages
http://code.activestate.com/recipes/410692/


# This class provides the functionality we want. You have need to look at
# this if you are want to know how this works. It only needs to be defined
# once, no need to muck around with its internals.
Class switch (object):
def __init__ (self, value):
Self.value = value
Self.fall = False

def __iter__ (self):
"" Return to 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, below
Self.fall = True
Return True
Else
Return False


# The following example is pretty the exact use-case of a dictionary,
# but is included to its simplicity. Note So 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 this to look as much as 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 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, 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): # "* 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!"

# Since Pierre ' s suggestion is backward-compatible with the original recipe,
# I have made the necessary modification to allow for the above usage.

---------------------------------------------------------------------------------------
Get the Site Type example:


Import Sys
From Urllib.parse import Urlparse

def getwebtype (URL):

r = Urlparse (URL)

Urldomain = R.netloc
URLPrefix = Urldomain.split ('. ') [0]

def www ():
return "www"
Def blog ():
Return "Blog blogs"
Def BBS ():
Return "BBS Forum"
Def Tieba ():
Return "Tieba paste"
Def wiki ():
Return "Wiki wiki"
Def baike ():
Return "Baike encyclopedia"
def img ():
Return "img Pictures"
Def ask ():
Return ' Ask question '
def other ():
Return to "other"

Web ={
"www": www,
"BBS": BBS,
"Wiki": Wiki,
"Baike": Baike,
"Tieba": Tieba,
"Iask": Ask,
"Ask": Ask,
"IMG": IMG,
"Image": IMG,
}
Return Web.get (Urlprefix,other) ()

url = ' Http://www.111cn.net '
Webtype = Getwebtype (URL)
Print (Webtype)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.