PYTHON_TIPS[1]-Using Python's dictionary to implement the Switch function

Source: Internet
Author: User

using the Python dictionary to implement the Switch function

Python is not a switch statement, when encountering the need to implement the switch statement function, generally can be replaced with if/else, but there is a more concise implementation method, the use of a dictionary implementation, the need to select the condition set to the dictionary key, the selected result is set to a value, The function of switch is realized by using the dictionary key to obtain the value.

1 defHello ():2     Print('hello!')3 4 defWorld ():5     Print('world!')6 7D = {'Hello': Hello,8      ' World': World}9 Ten deffoo (case): One     returnD[case] A  -Foo'Hello')() -Foo' World')()

Code Run Results

Hello! world!

Use a dictionary to implement a function similar to Switch.

PYTHON_TIPS[1]-Using Python's dictionary to implement the Switch function

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.