How to use Match/Case ( a good alternative for if statements )

Now it is very simple to use Match/Case since well, Match is literally to match the user’s input. Case is well, you create a case. If this case matches the user input, then it executes the code thats after the case.

Here is an example

inp = input('Hey there, Testing Case and Match!')
match inp:
  case '3': #Basically its. if this case matches <insert something here lolz >
    print('Well, yeah. 3, thats about it.')
  case '1':
    print('Yeah. 1, probably not my fav number but okay?')
#Note, there is NO else in here.

side note: this is the default case:

case _:
  <insert code to execute>

using match and case as an alternative for if statements is great. Since beginners can understand better about the alternatives for if statements. It can also save time when writing alot of ifs, elifs,etc. This can also make your code look neat and tidy, not some messy code. Heres the difference:

inp = inp = input('Hey there, Comparing some stuff!')
if inp == '3':
  print('Yeah its just a test')
elif inp == '1':
  print('Yeah, 1. But its just a test lolz')

Honestly, its just way more neat and it makes stuff easier since theres some errors you can make if you use if statements ( eg. inp = ‘1’ instead of inp == ‘1’ or inp == 1 instead of inp == ‘1’ )

Thats how you properly use Match/Case.
If you read all this, Thank you! And maybe you should go edit your code and put this in!

1 Like

Also add that the default case is

case _:

not

default:

as I though it’d be.

2 Likes

that still doesn’t show the potential of match-case. I could just keep my pre-3.10 code:

print(
    {
        "1": "Yeah. 1, probably not my fav number but okay?",
        "3": "Well, yeah. 3, thats about it.",
    }.get(input("Hey there, testing match-case!"), "default here")
)

But see

This is genius lol, never would have thought about using dictionaries like this

Why?

That’s a very cool solution. I opened the topic A better way to check inputs, and I honestly preferred the dictionary over the match/case, because it was just basically “shortened if-statements” if even that, and you are easily able to develop functions that make the process even faster, compared to using if-statements and match/case. Even though there is probably more functionality, match/case does not seem to be a good option for checking inputs.

1 Like