산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> python

Python 조건문 마스터하기: IF, ELSE, ELIF, 스위치류 로직

Python에서 조건문이란?

조건문은 불리언 표현식에 따라 다른 코드 블록 실행 가능하게 합니다. Python에서 if 문이 이 의사결정 과정을 이끄는 핵심 구조입니다.

이 가이드에서 if, else, elif, Python의 딕셔너리 기반 스위치-케이스 대안 사용법 탐구. 각 섹션에 개념 설명용 간결 예제 포함.

Python if 문 기초

문법

if expression:
    # 표현식이 True일 때 실행 블록
else:
    # 표현식이 False일 때 실행 블록

예제:

def main():
    x, y = 2, 8
    if x < y:
        st = "x is less than y"
    else:
        st = "x is not less than y"
    print(st)
if __name__ == "__main__":
    main()

if 조건이 거짓일 때

조건이 False로 평가되고 else 절 없으면 if 본문 건너뛰고 블록 뒤부터 계속 실행.

실패 조건 예제:

def main():
    x, y = 8, 4
    if x < y:
        st = "x is less than y"
    else:
        st = "x is greater than or equal to y"
    print(st)
if __name__ == "__main__":
    main()

else 절 사용

else 블록은 앞선 if 조건이 False일 때 실행. 이진 결정 시 유용.

def main():
    x, y = 8, 4
    if x < y:
        st = "x is less than y"
    else:
        st = "x is greater than y"
    print(st)
if __name__ == "__main__":
    main()

else 흔한 실수

두 값이 같을 때 else 블록이 비교를 '크다' 또는 '작다'로 잘못 보고할 수 있음.

def main():
    x, y = 8, 8
    if x < y:
        st = "x is less than y"
    else:
        st = "x is greater than y" # x == y일 때 부정확
    print(st)
if __name__ == "__main__":
    main()

elif로 다중 분기 도입

elif 절은 초기 if 뒤 추가 조건 테스트 허용. 위 낙하 오류 방지.

def main():
    x, y = 8, 8
    if x < y:
        st = "x is less than y"
    elif x == y:
        st = "x is the same as y"
    else:
        st = "x is greater than y"
    print(st)
if __name__ == "__main__":
    main()

삼항 표현식으로 로직 압축

Python 한 줄 문법으로 단순 비교 간결화:

def main():
    x, y = 10, 8
    st = "x is less than y" if x < y else "x is greater than or equal to y"
    print(st)
if __name__ == "__main__":
    main()

중첩 if 문

결정이 여러 변수에 의존할 때 중첩 조건 유용.

total = 100
country = "AU" # "US"로 변경해 다른 블록 테스트
if country == "US":
    if total <= 50:
        print("Shipping Cost is $50")
    elif total <= 100:
        print("Shipping Cost is $25")
    elif total <= 150:
        print("Shipping Costs $5")
    else:
        print("FREE")
elif country == "AU":
    if total <= 50:
        print("Shipping Cost is $100")
    else:
        print("FREE")

Python에서 스위치-케이스 대안

Python에 네이티브 switch 문 없지만 딕셔너리 조회로 같은 명확성과 효율성 제공.

def switch_example(argument):
    switcher = {
        0: "This is Case Zero",
        1: "This is Case One",
        2: "This is Case Two",
    }
    return switcher.get(argument, "nothing")
if __name__ == "__main__":
    argument = 1
    print(switch_example(argument))

요약

python

  1. C# 조건문 완전 정복: if, if-else, if-else if, 중첩 if 문법과 예제
  2. C# switch 문 마스터하기: 문법, 예제, 모범 사례
  3. C++ switch-case 문 마스터하기: 문법, 흐름, 실전 계산기 예제
  4. C 조건문 마스터: if, else, 중첩 완벽 이해
  5. C switch 문 마스터: 문법, 흐름, 실전 계산기 예제
  6. 파이썬 문장, 들여쓰기, 주석: 명확한 가이드
  7. 파이썬 if…else 문 마스터하기
  8. 파이썬 pass 문 마스터하기: 실전 가이드
  9. C++ switch-case 마스터하기: 문법, 활용법, 실전 예제
  10. Python print() 함수 완벽 가이드: 예제와 고급 기법