Why Python doesn't need a three-mesh operator and switch

Source: Internet
Author: User
Here's a small piece to bring you a brief discussion of why Python does not need three mesh operators and switch. Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.

For the trinocular operator (ternary operator), Python can be replaced with conditional expressions

For example, x<5?1:0 can be implemented in the following way

1if X<5else 0

NOTE: Conditional expressions was introduced before Python 2.5, so the above code is only available for 2.5 and later versions

For versions prior to 2.5, you can use the following form

X<5and1or 0

For switch, we can use dictionary to achieve, see the following example

>>>def switch (choice): Return Dict (Enumerate (range (4))) [choice]>>> switch (1) >>> switch (0 ) values = {  value1:do_something1,  value2:do_something2,  ...  VALUEN:DO_SOMETHINGN,  }values.get (Var, do_default_something) ()

The above is a small series for everyone to talk about why Python does not need three mesh operator and switch all the content, I hope you support topic.alibabacloud.com~

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.