stay 《Python in if How to use statements 》 I mentioned , For a possibility 、 Two or more possibilities , Can pass if Statement to implement . While using if Statement implements multiple possibilities , You need more than one elif sentence , This makes the code look cluttered , It can also be done through match Statement to implement multiple possibilities , And the code looks much cleaner .
match The syntax of the statement is as follows
match Variable / expression :
case value 1:
sentence 1
case value 2:
sentence 2
case value 3:
sentence 3
...
case _:
sentence n
among ,match Followed by variables or expressions , and case This is followed by the possible values of the variable or expression , When its value is a value 1 when , Then execute the statement 1, When its value is a value 2 when , Then execute the statement 2, And so on . If the value of the variable or expression is not in case Statement , execute “case _” The following sentence n.
match The basic usage of the statement is shown in the figure 1 Shown
chart 1 match Usage of sentences
among , Variable i The value of is 1,match Statement according to the variable i Different values of , Different statements will be executed . here , The output of the program is “i=1”, If the variable i Is set to 3, When the code is executed again , Will perform “case _” The following sentence , The output “i The value of is not within the specified range ”.
In the use of match When the sentence is , There are two things to note ,
(1) Note the use of colons
stay match Statement and case After statement , Must have a colon .
(2) Pay attention to indenting
stay match Statement and case Code after statement , Must be indented .