Skip to content
Advertisement

Match True in python

In JavaScript, using the switch statement, I can do the following code:

JavaScript

And it’s going to return 1, since JavaScript switch is comparing true === (1 === 1)

But the same does not happen when I try it with Python Match statement, like as follows:

JavaScript

It returns:

JavaScript

And another error is returned if I try it this way:

JavaScript

It returns:

JavaScript

What would be the cleanest/fastest way to do many different checks without using a lot of if’s and elif’s?

Advertisement

Answer

In JavaScript, using the switch statement, I can do the following code

I definitely wouldn’t be using JavaScript as any form of litmus or comparator for python.


If you used 1==1 in your first test case, the below is what both of your test cases are ultimately doing.

JavaScript

This is why you get the error for the second version. True will only ever be True, so no other case will ever be hit.

Based on your example, it seems like you are trying to use match/case just to determine the “truthiness” of an expression. Put the expression in the match.

JavaScript

If you have a lot of expressions, you could do something like the below, although I don’t think this is very good.

JavaScript

cases should be possible results of the match, NOT expressions that attempt to emulate the match. You’re doing it backwards. The below link should tell you pretty much everything that you need to know about match/case, as-well-as provide you with alternatives.

Match/Case Examples and Alternatives

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement