Python Tips -06

match..case statement in PYTHON

The latest Python starting from Python 3.10, a match..case structure has been introduced as an alternative to switch..case in other languages.

Syntax:

match term:

    case pattern-1:

         action-1

    case pattern-2:

         action-2

    case pattern-3:

         action-3

....

    ....

case pattern-n:

action-n

    case _:

        default-action

statement - x

If any pattern (pattern-1, pattern-2, pattern-3, ..., pattern-n) starting from pattern-1 is matched with the term, then the corresponding action will be performed, and after that, the statement following the match..case will execute. i.e., statement-x. If none of the patterns match, case _ (underscore symbol defines the default case in Python) will execute.

Note: The keywords are marked in boldface. There is no break as in the c/c++/java switch..case statement.

Examples:

#Exercise - 01
#Print the career opportunity for the given computer languages.
lang = input("What programming language you are interested to learn?")

match lang:

    case "JavaScript":

        print("You can become a web developer.")

    case "Python":

        print("You can become a Data Scientist")

    case "PHP":

        print("You can become a backend developer")

    case "Solidity":

        print("You can become a Blockchain developer")

    case "Java":

        print("You can become a mobile app developer")

    case _:

        print("The language doesn't matter, what matters is solving problems.")


Suppose if the input by the user is Python; then the output is


You can become a Data Scientist


#Exercise - 02

# Print the word equivalent of a single-digit number


no= int(input("Enter a number"))

match no:

    case 0:

        print("Zero")

    case 1:

        print("One")

    case 2:

        print("Two")

    case 3:

        print("Three")

    case 4:

        print("Four")

    case 5:

        print("Five")

    case 6:

        print("Six")

    case 7:

        print("Seven")

    case 8:

        print("Eight")

    case 9:

        print("Nine")

    case _:

        print("Not a single digit number")


            Suppose, if the input is 10, the case _ will execute and it will print "Not a single digit number"

....HAPPY LEARNING....

Comments

Popular posts from this blog

C Puzzle

Python Tips - 03