Notebook

これは日々の作業を通して学んだことや毎日の生活で気づいたことをを記録しておく備忘録である。

HTML ファイル生成日時: 2025/07/30 08:17:51.269 (台灣標準時)

Python の match statement と case statement

Python の "The Python Tutorial" を読んでいたら、 match statement と case statement についての記述があったでござる。「Pythonにそんなものがあったでござろう か」と思って調べてみたら、 Python 3.10で新た に使えるようになったものでござった。

まだ Python 3.9 を使い続けているので、 Python 3.10 をインストールして、 match と case を試してみたでござる。以下のようなコードを用意してみたで ござる。


#!/usr/pkg/bin/python3.10

#
# Time-stamp: <2022/08/31 15:33:26 (CST) daisuke>
#

# importing sys module
import sys

# if the number of command-line argument is not one, then quit
if ( len (sys.argv) != 2 ):
    print ("Give one command-line argument!")
    sys.exit ()

# converting a command-line argument into an integer
try:
    n = int (sys.argv[1])
except:
    print ("%s is not an integer!" % sys.argv[1])
    sys.exit ()

# use of match and case statements
match n:
    case 0:
        print ("n is equal to 0.")
    case 1:
        print ("n is equal to 1.")
    case _:
        print ("n is neither equal to 0 or 1.")

上のコードを実行してみると、以下の通りにござる。


% ./test_match_00.py 0
n is equal to 0.
% ./test_match_00.py 1
n is equal to 1.
% ./test_match_00.py 2
n is neither equal to 0 or 1.
% ./test_match_00.py -3
n is neither equal to 0 or 1.

Python 3.10 で新たに加わった機能だからなのか、 Emacs を使って match と case を含むコードを書くと、 match や case がインデントの対象にならない でござる。

fig_202208/python_match_00.png
fig_202208/python_match_01.png


Frequently accessed files

  1. Misc___Taiwan/20240819_00.html
  2. Misc___Taiwan/20240207_00.html
  3. Computer___TeX/20231107_00.html
  4. Computer___Network/20230516_00.html
  5. Computer___NetBSD/20230119_00.html
  6. Computer___NetBSD/20250301_01.html
  7. Computer___NetBSD/20240805_03.html
  8. Food___Taiwan/20230608_04.html
  9. Misc___Taiwan/20240903_01.html
  10. Food___Taiwan/20230609_06.html
  11. Computer___NetBSD/20250728_00.html
  12. Computer___Network/20230726_00.html
  13. Misc___Taiwan/20250728_01.html
  14. Food___Taiwan/20220605_4.html
  15. Computer___TeX/20240410_00.html
  16. Computer___NetBSD/20250409_00.html
  17. Misc___Taiwan/20220831_4.html
  18. Computer___Python/20240101_00.html
  19. Computer___Hardware/20250319_00.html
  20. Food___Taiwan/20230711_15.html
  21. Computer___TeX/20230726_01.html
  22. Food___Taiwan/20220811_9.html
  23. Food___Taiwan/20230604_00.html
  24. Food___Taiwan/20230622_10.html
  25. Computer___Network/20241214_00.html
  26. Food___Taiwan/20230724_00.html
  27. Food___Cooking/20230625_03.html
  28. Travel___Taiwan/20230525_09.html
  29. Computer___FreeBSD/20240123_00.html
  30. Food___Cooking/20220821_5.html


HTML file generated by Kinoshita Daisuke.