程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Usage of match statement in Python

編輯:Python

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 .

1 match Sentence syntax

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.

2 match Usage of sentences

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 ”.

3 match Notes on sentences

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved