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
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
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)()
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!