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 :: __repr__ in python 
Python :: tkinter change button color smoothly 
Python :: python list object attributes 
Python :: how many numbers greater than 100 using pytho 
Python :: #find the difference in days between two dates. 
Python :: django queryset and operator 
Python :: values django 
Python :: python regex validate phone number 
Python :: use functions to resample pandas 
Python :: guardar plot python 
Python :: pandas removing outliers from dataframe 
Python :: create jwt token in django 
Python :: Pandas Columns Calling 
Python :: No installed app with label 
Python :: scikit learn library in python 
Python :: enum python string 
Python :: éliminer le background image python 
Python :: tkinter how to update optionmenu contents 
Python :: login page in python flask with database 
Python :: list of dictionary values 
Python :: # read table data from PDF into dataframe and save it as csv or json 
Python :: get single batch from torch data loader 
Python :: python closing socket good way 
Python :: pyqt button hover color 
Python :: Pillow opencv convert RGB to BRG or RGB to BRG 
Python :: how to print list without newline 
Python :: Prints all integers of a list 
Python :: increment dic with for loop 
Python :: python manage.py collectstatic 
Python :: Getting the string and the regex of the matched object 
ADD CONTENT
Topic
Content
Source link
Name
2+7 =