0

Python match clause

Do our sololearn python version support match clause (switch clause in c++ or case var of ) as in Pascal?

23rd Jan 2024, 4:33 AM
Oliver Pasaribu
4 Respuestas
+ 6
import platform print(platform.python_version()) Sololearn's Python as of now is 3.9.16 switch case is 3.10 upwards
23rd Jan 2024, 5:10 AM
Bob_Li
Bob_Li - avatar
+ 1
Oliver Pasaribu , Pydroid 3 (the Android app for running Python 3) has upgraded to 3.11.4 now, so I played around with the match compound statement there. import random n = random.randint(1, 4) # (inclusive) match n: case 1: print(n, "is one.") case 2: print(n, "is two.") case _: # _ always matches. print(n, "isn't one or two.") Possible outputs: 1 is one. 2 is two. 3 isn't one or two. 4 isn't one or two. One thing notable is that it adds another special-case use of the _ symbol to the language.
23rd Jan 2024, 5:52 PM
Rain
Rain - avatar
+ 1
also, the cases automatically break out of the match clause if a match is found, so no need to add the 'break' keyword to each case, something that is common in other languages. You can also use conditional if statements in the pattern, as well as match wildcards, dictionary key values, etc... It is a step above simple switch case, and more versatile than if-else.
23rd Jan 2024, 11:26 PM
Bob_Li
Bob_Li - avatar
+ 1
Ok, Bob_Li and Rain,thank you for your information.
24th Jan 2024, 2:28 AM
Oliver Pasaribu