Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

match case in Python

>>> command = 'Hello, World!'
>>> match command:
...     case 'Hello, World!':
...         print('Hello to you too!')
...     case 'Goodbye, World!':
...         print('See you later')
...     case other:
...         print('No match found')
 
Hello to you too!
Comment

python match case example

match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case <pattern_3>:
        <action_3>
    case _:
        <action_wildcard>
Comment

python match case

x = 4

# x is the variable to match
match x:

    # if x is 0
    case 0:
        print("x is zero")

    # case with if-condition
    case 4 if x % 2 == 0:
        print("x % 2 == 0 and case is 4")

    # Empty case with if-condition
    case _ if x < 10:
        print("x is < 10")

    # default case(will only be matched if the above cases were not matched)
    # so it is basically just an else:
    case _:
        print(x)



# WHAT THE CODE WOULD LOOK LIKE IF IT DIDN'T USE MATCH/CASE

x = 4

if x == 0:
	print("x is zero")
elif x == 4 and x % 2 == 0:
	print("x % 2 == 0 and case is 4")
elif x < 10:
	print("x is < 10")
else:
	print(x)
Comment

PREVIOUS NEXT
Code Example
Python :: argsort in descending order numpy 
Python :: python list insert vs append 
Python :: Python Try Except Else Clause 
Python :: python try 
Python :: use model from checkpoint tensorflow 
Python :: how to check system has internet using python 
Python :: #Check if list1 contains all elements of list2 using all() 
Python :: Average of total in django querysets 
Python :: seaborn bar plot sort for weekday 
Python :: python parse /etc/resolv.conf 
Python :: flask production server 
Python :: how to uninstall python-dotenv 
Python :: pair plot seaborn 
Python :: how to make a bot send whatever you dm it into a server discord.py 
Python :: Python __floordiv__ 
Python :: dependency inversion 
Python :: python list insert 
Python :: pyqt popup yes no 
Python :: using polymorphism in python 
Python :: python function overloading 
Python :: Converting a HDFDataset to numpy array 
Python :: remove SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame 
Python :: includes python 
Python :: Sqlalchemy Define class from existing table 
Python :: typer python 
Python :: python genap ganjil 
Python :: explode multiple columns pandas 
Python :: loading bar python 
Python :: check if value is in list python 
Python :: pandas flip x and y axis 
ADD CONTENT
Topic
Content
Source link
Name
2+5 =