Uncategorized

13:Decision – I (match-case)

Decision – I (match-case)

Decision making is an important aspect of computer programming. It helps us to execute wisely. We can select the statements to execute on runtime.

  1. Simple algorithms can be written with help of variables and operations but most algorithms require decision making.
  2. By decision making we can force the execution for a specific part of the program that makes the program intelligent.
  3. There are many decision-making statements in Python and match-case is one of these.
  4. match-case is quite new in Python. It was introduced in version 3.10.
  5. In match-case structure, computers have to select exactly one option in multiple choices.
  6. The statements under this option will execute and all other statements will be skipped.
x = int (input ("Enter a number: "))match x:    case 1:        print ("x is 1")    case 2:         print ("x is 2")    case 3:        print ("x is 3")    case _:        print ("x is something else")

Code 1: Basic flow of match-case

  1. First, we enter a value into variable x.
  2. In match statement x is set up (line 2). If multiple variables are used in a program, then the match-case must know which is the decision variable.
  3. In the next lines there are multiple case statements.
  4. The computer will match the value of x to the case.
  5. In which case the value matches, only statement(s) under it will execute.
  6. For example, the user will enter 2 that will store in the x.
  7. Now in match, the system will start matching and it will match with case 2.
  8. Now the statement print (“x is 2”) will execute.
  9. Here is the only one statement under each case but it is possible that more than one statement can exist.
  10. If no statement matches then the case _ will be executed.
  11. The operator “:” defines a block of code on the next line.
  12. Must provide indentation in case and statements.
  13. match-case can also check the data type.
x = int (input ("Enter a number: ")) match x:    case int ():        print ("x is integer")    case float ():         print ("x is float")    case str ():        print ("x is string")    case bool ():        print ("x is Boolean")    case _ ():	  print ("x is something else")

Code 2: Using Type Check by match-case

Real World Examples

Example 1: Write a program that takes two numbers from the user. The user will also enter a choice about these numbers that what he/she wants with these numbers. The choices are addition, subtraction, multiplication, division and exponent.

Solution:

  1. Pseudocode as follows.
  2. Create two variables (integers) and ask the user to enter the values of these variables.
  3. Print five choices which are defined in problem
  4. 1 – Addition
  5. 2 – Subtraction
  6. 3 – Multiplication
  7. 4 – Division
  8. 5 – Power
  9. Create another variable (integer) that will ask the user to enter. This is choice variable
  10. if the user entered choice 1 then calculate the sum of variables (created in first step).
  11. Store it and display
  12. Similarly, if a user enters 2 then calculate the difference using subtraction operator, store it and display.
  13. So forth for next choices.
  14. Create a new file in VS Code.
  15. Name it “simple_calc.py”.
  16. Writing the following code in it.
number1 = int (input ("Enter first number: "))number2 = int (input ("Enter second number: "))print ("1 - Add")print ("2 - Subtract")print ("3 - Multiply")print ("4 - Divide")print ("5 - Power")choice = int (input ("Enter your choice: "))match choice:    case 1:         ans = number1 + number2        print (f"The sum is: {ans}")    case 2:         ans = number1 - number2        print (f"The difference is: {ans}")    case 3:        ans = number1 * number2        print (f"The product is: {ans}")    case 4:        ans = number1 / number2        print (f"The quotient is: {ans}")    case 5:        ans = number1 ** number2        print (f"The power is: {ans}")    case _:        print ("Invalid choice, please select a valid operation.") print ("Program finished.")

Code 3: Creating Simple Calculator

  1. On the first two lines, we create variables for numbers.
  2. On next 5 lines we display the choice chart for user
  3. On line 9, the program asks to enter a number for the choice (1, 2, 3, 4 or 5).
  4. Line 11 we start match-case.
  5. We have three variables in this program, two numbers and one for choice.
  6. We have mentioned the choice variable on line 11 for matching.
  7. From line 12 to 28 we write code for cases.
  8. Line 29 just prints that the program is closed.
  9. For example, users enter 2 and 5 respectively for numbers and choose 3 (multiplication) as operation choice.
  10. The case 3 will be matched and all statements (line 19 and 20) will execute here.
  11. The numbers will be multiplied and 10 will print and the program will finish because no other case will match here.
  12. match-case is nested able. You can add more match-case inside a case if required.
  13. Code blocking is also an important lesson we should learn here.
  14. When the symbol “:” is used after some statement in Python; like line 11 or 12 then it means a new block is starting.
  15. Must provide indent on the next line.
  16. You can see that the match statement was line 11. The line 12 has four spaces indented because the case 1 is the sub-statement of match.
  17. Similarly, the line 12 also has “:” operator so, the next line 13 indents more.
  18. All the statements which get indent considered as sub-statements and required to execute if code block execute.
  19. For example, all the case statements from line 12 to line 27 have four spaces indented. It means all these statements are under the match statement of line 11.
  20. Similarly, the statements on line 13 and 14 are indented more because they sub-statement of case 1 (line 12).
  21. You can also observe that line 29 has no indent like line 28 because we want to run this statement out of match code block.
  22. This indentation is compulsory in Python.
  23. We don’t need to type this indent ourselves, the VS code automatically applies this.

Leave a Reply

Your email address will not be published. Required fields are marked *