Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python의 스위치 케이스(대체)

<시간/>

이 튜토리얼에서는 Python에서 스위치 케이스 역할을 하는 프로그램을 작성할 것입니다.

C, C++, Java와 같은 기타 프로그래밍 언어 등.. 스위치가 있는 반면 Python 하지 않습니다. Python에서 스위치 케이스 역할을 하는 프로그램을 작성해 봅시다.

파이썬에서 스위치 케이스를 작성하기 위해 dict 데이터 구조를 사용할 것입니다. 다음 코드를 보자.

# dictionary with keys and values
days = {
   0: 'Sunday',
   1: 'Monday',
   2: 'Tuesday',
   3: 'Wednesday',
   4: 'Thursday',
   5: 'Friday',
   6: 'Saturday'
}
# we will use 'get' method to access the days
# if we provide the correct key, then we will get the corresponding value
# if we provide a key that's not in the dictionary, then we will get the defaul
lue
print(days.get(0, 'Bad day'))
print(days.get(10, 'Bad day'))

출력

위의 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.

Sunday
Bad day

우리는 가치 대신에 무엇이든 둘 수 있습니다. get의 기본값 메소드는 기본을 나타냅니다. 대소문자를 바꾸는 키워드입니다.

결론

튜토리얼에 의문점이 있으면 댓글 섹션에 언급하세요.