Python में match Statement
In this page:
match subject:
case pattern1:
# block 1
case pattern2 | pattern3:
# block 2
case _:
# default
बेसिक Match-Case
Python 3.10 में introduce किया गया, match/case एक value की तुलना patterns की एक series से करता है और पहले match के लिए block चलाता है -- यह elif ladder की तुलना में एक lookup table जैसा दिखता है, खासकर जब आप दो-तीन से ज़्यादा cases जाँच रहे हों।
उदाहरण: Basic Match-Case
command = "start"
match command: # compares command against each case pattern
case "start":
print("Starting")
case "stop":
print("Stopping")
Wildcard Fallback (case _)
underscore _ एक catch-all pattern की तरह काम करता है जो हमेशा match करता है, बिल्कुल वैसे ही जैसे if/elif ladder में अंतिम else काम करता है -- Python का linter आपको यह भी warn करता है अगर किसी match block में यह missing हो और बिना किसी match के fall through हो सकता हो।
उदाहरण: Wildcard Fallback (case _)
command = "pause"
match command:
case "start":
print("Starting")
case _: # catch-all pattern, matches anything not matched above
print("Unknown command")
| से Cases को Group करना
case के अंदर | operator कई values को group करता है जिन्हें एक ही block trigger करना चाहिए, जैसे case "y" | "yes":, इससे एक जैसा काम करने वाले अलग-अलग duplicate cases लिखने की ज़रूरत नहीं पड़ती।
उदाहरण: Grouping Cases with |
answer = "y"
match answer:
case "y" | "yes": # | groups multiple values for the same case
print("Confirmed")
case _:
print("Not confirmed")
Guards के साथ Match-Case
किसी pattern के बाद if clause जोड़ना -- जिसे guard कहा जाता है -- किसी case को तभी match करने देता है जब pattern *और* एक extra condition दोनों सच हों, जैसे case n if n > 0:, यह structural matching को एक साधारण boolean जाँच के साथ जोड़ता है।
उदाहरण: Match-Case with Guards
n = 5
match n:
case n if n > 0: # guard: pattern matches n, and the if condition must also hold
print("Positive")
case _:
print("Not positive")
Sequences को Match करना
साधारण value matching से आगे बढ़कर, match pattern के अंदर ही sequences को सीधे destructure कर सकता है -- case [x, y]: एक लाइन में x और y को दो-element वाली list के contents से bind कर देता है, ऐसा कुछ जो elif ladder उतनी सफ़ाई से express नहीं कर पाती।
उदाहरण: Matching Sequences
point = [3, 4]
match point:
case [x, y]: # destructures the two-element list into x and y
print(x, y)
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: