logo

Python의 대소문자 전환(대체)

이번 글에서는 Python의 Switch Case(Replacement)를 이해해 보겠습니다.

Python에서 Switch Case를 대체하는 것은 무엇입니까?

이전에 사용했던 다른 모든 프로그래밍 언어와 달리 Python에는 스위치나 Case 문이 없습니다. 이 사실을 해결하기 위해 사전 매핑을 사용합니다.



방법 1: 사전 매핑을 사용하여 Python에서 케이스 전환 구현

Python에서 사전은 데이터 값을 저장하는 데 사용할 수 있는 데이터 값의 정렬되지 않은 모음입니다. 요소당 단일 값만 포함할 수 있는 다른 데이터 유형과 달리 사전에는 키:값 쌍도 포함될 수 있습니다.
핵심 가치는 사전 데이터 유형은 사전을 사용하여 Switch Case 문을 대체할 때 Switch 문의 Case로 작동합니다.

파이썬3






특수문자 이름



# Function to convert number into string> # Switcher is dictionary data type here> def> numbers_to_strings(argument):> >switcher>=> {> >0>:>'zero'>,> >1>:>'one'>,> >2>:>'two'>,> >}> ># get() method of dictionary data type returns> ># value of passed argument if it is present> ># in dictionary otherwise second argument will> ># be assigned as default value of passed argument> >return> switcher.get(argument,>'nothing'>)> # Driver program> if> __name__>=>=> '__main__'>:> >argument>=>0> >print> (numbers_to_strings(argument))>

>

>

산출

zero>

방법 2: if-else를 사용하여 Python에서 Case 전환 구현

그만큼 다른 경우라면 스위치 케이스 교체를 구현하는 또 다른 방법입니다. 특정 명령문이나 명령문 블록이 수행되는지 여부, 즉 특정 조건이 true인 경우 명령문 블록이 실행되는지 여부를 결정하는 데 사용됩니다.

파이썬3


경찰 부국장



bike>=> 'Yamaha'> if> bike>=>=> 'Hero'>:> >print>(>'bike is Hero'>)> elif> bike>=>=> 'Suzuki'>:> >print>(>'bike is Suzuki'>)> elif> bike>=>=> 'Yamaha'>:> >print>(>'bike is Yamaha'>)> else>:> >print>(>'Please choose correct answer'>)>

>

>

산출

bike is Yamaha>

방법 3: 클래스를 사용하여 Python에서 케이스 전환 구현

이 메서드에서는 클래스를 사용하여 Python 스위치 내부에 스위치 메서드를 만듭니다. 파이썬의 클래스 .

파이썬3




균일한 혼합물
class> Python_Switch:> >def> day(>self>, month):> >default>=> 'Incorrect day'> >return> getattr>(>self>,>'case_'> +> str>(month),>lambda>: default)()> >def> case_1(>self>):> >return> 'Jan'> >def> case_2(>self>):> >return> 'Feb'> >def> case_3(>self>):> >return> 'Mar'> my_switch>=> Python_Switch()> print>(my_switch.day(>1>))> print>(my_switch.day(>3>))>

>

>

산출

Jan Mar>

Python의 대소문자 전환

Python 3.10 이상에서는 Python이 다음을 사용하여 이를 지원합니다. 성냥 스위치 대신:

파이썬3


행 대 열



# This code runs only in python 3.10 or above versions> def> number_to_string(argument):> >match argument:> >case>0>:> >return> 'zero'> >case>1>:> >return> 'one'> >case>2>:> >return> 'two'> >case default:> >return> 'something'> > head>=> number_to_string(>2>)> print>(head)>

>

>

C++, Java 등의 스위치 케이스와 유사합니다.