
Please support if you like my work by payment through upi: sinhamit@icici or payment by bank
account name: Amit Kumar Sinha,
account number: 2646728782
IFSC code: KKBK0005660
SWIFT: KKBKINBB
match case keywords in Category: Python by amit
🕙 Posted on 2023-09-20 at 01:30:21 Read in Hindi ...
Some Reserved Keywords
You have already seen various reserved keywords, for example, and, or, not, is, in, for, while, if, elif, else, break, continue, del and import. Reserved keywords and built-in functions are core (functionalities) of Python programming. Many modules, such as math, operator, random, turtle, tkinter, etc. are already installed when you have installed the Python software, but these modules are not automatically available for operations or usage.
This separation of different modules from core Python application is done for optimization of your scripts (codes written in yourFileName.py file) and avoiding unnecessary inclusion of other modules. To know more about any module, you have to first import that module, and thereafter, you can type dir( name_of_module ) or print( dir( name_of_module ) ) either in Python CLI >>> or execute scripts (saved in yourFileName.py file) from Command Prompt/
Example 1
import keyword
print( dir(keyword) ) # To know how many, and which methods are available in a module. Output is shown below.
print() # It creates a new line between above and below statements.
print( keyword.kwlist, '\n', type(keyword.kwlist), '\n') # It shows all reserved keywords in a list data-type. Output is shown below.
print( keyword.softkwlist, '\n', type(keyword.softkwlist), '\n' ) # It shows keywords in context in a list data-type. Output is shown below.
print( dir(keyword.kwlist) ) # It does not show list of keywords, but all methods of the output data-type, that is, list.
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
<class 'list'>
['_', 'case', 'match']
<class 'list'>
When you have installed the Python application, as instructions provided in previous page, you have checked on ☑ Documentation option. Thus, you can find the python3109.chm file (for Python 3.10.9) or python3913.chm file (for Python 3.9.13) or html folder (for Python 3.11.5) in the doc folder (inside the folder where you have installed the Python software). You should also visit official https://doc.
I have installed at least three versions of Python software in my PC, that is, Python 3.9.13, Python 3.10.11, and Python 3.11.5. You may have to install different versions of Python in your remote servers/PC or also in your local computer, when you will learn Cloud Computing, Machine Learning, or deploy your sofisticated WEB-APPLICATION on an INSTANCE (a remote OS installed by you on different Cloud Service Providers).
Since reserved keywords are core of Python software, you can see in above result that only kwlist and softkwlist are available methods. Also, iskeyword and issoftkeyword methods are available to check whether any string literal is a reserved/
Example 2
import keyword # You should import a module only once in a file.
print( keyword.iskeyword('else') ) # Outputs True
print( keyword.iskeyword('match') ) # Outputs False
print( keyword.issoftkeyword('match') ) # Outputs True (introduced in Python 3.10, outputs False in previous versions.)
import keyword # keyword module is just like builtins module, both of which are used to display names of reserved keywords, built-in functions, and their respective documentation.
print( help( yield ) ) # Outputs ERROR, though you have written import keyword at the top of your file, new.py
# Some keywords, such as None, True etc. will not throw ERROR, and display documentation about them, when you execute help( None ) or help( True ) but placing most reserved keywords inside help() will throw SyntaxError: invalid syntax.
print( help( keyword.yield ) ) # also Outputs ERROR
Example 3
import keyword
j = 0
for i in keyword.kwlist:
print( str(j) + ' ' + i )
j = j + 1
You can see the OUTPUT of above code (Example 3) on the right side.
The OUTPUT of Example 3 shows the index number of each keyword before them. You should use respective index numbers, to get help documentation of desired reserved keywords.
1 None
2 True
3 and
4 as
5 assert
6 async
7 await
8 break
9 class
10 continue
11 def
12 del
13 elif
14 else
15 except
16 finally
17 for
18 from
19 global
20 if
21 import
22 in
23 is
24 lambda
25 nonlocal
26 not
27 or
28 pass
29 raise
30 return
31 try
32 while
33 with
34 yield
Example 4
import keyword
print( help( keyword.kwlist[34] ) )
*********************
yield_stmt ::= yield_expression
A "yield" statement is semantically equivalent to a yield expression.
The yield statement can be used to omit the parentheses that would
otherwise be required in the equivalent yield expression statement.
For example, the yield statements
yield <expr>
yield from <expr>
are equivalent to the yield expression statements
(yield <expr>)
(yield from <expr>)
Yield expressions and statements are only used when defining a
*generator* function, and are only used in the body of the generator
function. Using yield in a function definition is sufficient to cause
that definition to create a generator function instead of a normal
function.
For full details of "yield" semantics, refer to the Yield expressions
section.
None
match case
Similarly, you can know about any of above reserved keywords. However, some new keywords, that is, match and case are introduced in Python 3.10. In the match case block, a variable name (assigned with number, string, boolean, or None) is placed after the match keyword, and it is checked with each case (option). Unlike if elif else block of codes, match case block checks the literal only once. Syntax of match case block is as follows:
Example 5
name = "user"
match name:
case "user":
print(f"Welcome {name}, you are in the class.")
case "public":
print("Sorry, you have to login first.")
case "unknown":
print("You have not registered to our class.")
A simple CLI App
In the following example, two, four, six, eight, ten blank spaces are left in sequence for respective level of indentations. Do not use Tab key in your keyboard, when writing codes in Text Wranggler (in Mac OS) or Notepad (in MS Windows OS), or other simple text-editors. It may cause IndentationError or SyntaxError. A empty list is created for adding notes in your simple CLI app, and it is assigned to variable name, my_notes. Thereafter, an infinite while loop will ask every time, your action to be taken. You can also use string literal, as described in above example 5, instead of integer option to be matched.
You should first type-cast the output of input() function to integer data-type, otherwise TypeError may be shown. You have to first check whether input data is numeric data-type or not (with isnumeric() string method). The user may press Enter or Return key without entering any number. This will assign the output an empty string to variable name user_action. Then, the int() built-in function will truncate the numeric data-type to integer, if the user inputs any floating (decimal) number. The continue statement under the (first) else will skip the while loop, and ask the user to enter a numeric value.
Thereafter, the match block starts, and you should peruse each case option separate from other cases. In this way, you will find the following example, a very simple CLI app, which will be modified in next chapters. More built-in functions and some custom functions will be added, with the help of def keyword. The first two cases are very simple, and they add and show items in the my_notes list. The third and fourth cases also include NESTED for loop, each of which shows a number before each item. The user will input the number for desired item, and it will be edited or deleted from the my_notes list.
Example 6
my_notes = []
while True:
user_action = input("Press 1 to add, 2 to show, 3 to edit, 4 to delete a note: ")
if user_action.isnumeric():
take_action = int(user_action)
else:
continue
match take_action:
case 1:
add_note = input("Enter your note here (when complete, press Enter or Return key): \n")
my_notes.append( add_note )
case 2:
print( "\n".join(my_notes) )
case 3:
if my_notes == []:
print("Your notebook is empty. Please add something.")
else:
for index, item in enumerate(my_notes):
print( index + 1, item )
edit_num = int(input("Enter the number of item to be edited: "))
my_notes[edit_num - 1] = input("Write something to edit: ")
case 4:
if my_notes == []:
print("Your notebook is empty. Please add something.")
else:
for index, item in enumerate(my_notes):
print( index + 1, item )
del_num = int(input("Enter the number of item to be deleted: "))
del my_notes[del_num - 1]
print( "\n".join(my_notes) ) # Or, you can display the deleted item here!
case _:
break
The _ (underscore) symbol is placed after the case keyword to select other (default) options, which are not mentioned in previous cases, and the user has opted them by mistake or deliberately. However, in the above example, since the string literals are already parsed by the first if block, the user can only input the numeric value for all options. When the user enters 5 or any number other than 1, 2, 3, 4 then the above program will be completed (or terminated).
The above example is not the finished version of the simple CLI app, and you can see that when the user enters any number other than items available in my_notes list for editing or deleting it, ERROR will be shown. You should try to insert if else block to check whether the input provided by the user is numeric or not. Also, you should try to check whether the number provided by the user is not more than last index number of that list. You can do it with the help of len() built-in function.
In next pages, you will learn to create custom functions, and save your notebook (that is, texts written by the user for each item of the my_notes list) in a file with .txt file. Hope, you have enjoyed the above example, and don't find it difficult. If you've any question regarding the same, you can mail me at help@ribhu.org.
Leave a Comment:
Amit Sinha March 2nd, 2023 at 9:30 PM
😃 😄 😁 😆 😅 😂 😉 😊 😇 😍 😘 😚 😋 😜 😝 😶 😏 😒 😌 😔 😪 😷 😵 😎 😲 😳 😨 😰 😥 😢 😭 😱 😖 😣 😞 😓 😩 😫 😤
Ribhu March 3rd, 2023 at 9:30 PM
🐵 🐒 🐶 🐩 🐺 🐱 🐯 🐅 🐆 🐴 🐎 🐮 🐂 🐃 🐄 🐷 🐖 🐗 🐽 🐏 🐑 🐐 🐪 🐫 🐘 🐭 🐁 🐀 🐹 🐰 🐇
