Home > Backend Development > Python Tutorial > Why python doesn't need ternary operator and switch

Why python doesn't need ternary operator and switch

高洛峰
Release: 2017-03-02 11:05:25
Original
1550 people have browsed it

The following editor will bring you a brief discussion on why python does not need the ternary operator and switch. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

For the ternary operator, python can use conditional expressions instead

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

1if x<5else 0
Copy after login

Note: conditional expressions were introduced before Python 2.5, so the above code only Applicable to 2.5 and later versions

For versions before 2.5, you can use the following form

X<5and1or 0
Copy after login

For switch, we can definitely Use dictionary to implement, look at 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)()  
Copy after login

The above is a brief discussion brought by the editor about why Python does not need the ternary operator and switch all Content, I hope everyone will support the PHP Chinese website~

For more articles about why Python does not need the ternary operator and switch, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template