Topic 2: 논리 연산자 - 복합 조건 다루기 🔗
🎯 학습 목표
논리 연산자(and, or, not)를 이해하고 활용하여 여러 조건을 조합한 복합 조건문을 작성할 수 있습니다.
🧠 논리 연산자의 필요성
실생활의 복합 조건
일상생활에서 우리는 여러 조건을 함께 고려합니다:
- “나이가 18세 이상이고 운전면허가 있으면 운전할 수 있다”
- “비가 오거나 눈이 오면 우산을 가져간다”
- “오늘이 주말이 아니면 알람을 맞춘다”
프로그래밍에서도 여러 조건을 조합해야 할 때가 많습니다.
단순 조건의 한계
# 조건을 따로따로 체크하면...
age = 20
has_license = True
if age >= 18:
if has_license:
print("운전 가능")
else:
print("면허 필요")
else:
print("운전 불가")
# 논리 연산자를 사용하면...
age = 20
has_license = True
if age >= 18 and has_license:
print("운전 가능")
else:
print("운전 불가")
🔗 and 연산자 - “그리고”
and의 특징
모든 조건이 참이어야 전체가 참
print(True and True) # True
print(True and False) # False
print(False and True) # False
print(False and False) # False
실용 예시
# 대학 입학 조건
age = int(input("나이: "))
score = int(input("점수: "))
if age >= 18 and score >= 80:
print("입학 가능합니다")
else:
print("입학 조건을 만족하지 않습니다")
# 영화관 입장 조건
age = int(input("나이: "))
has_ticket = input("티켓 있나요? (y/n): ")
if age >= 12 and has_ticket == "y":
print("입장 가능합니다")
else:
print("입장 불가능합니다")
여러 조건 조합
username = input("사용자명: ")
password = input("비밀번호: ")
is_active = True
if username == "admin" and password == "1234" and is_active:
print("로그인 성공!")
else:
print("로그인 실패!")
🌟 or 연산자 - “또는”
or의 특징
하나라도 조건이 참이면 전체가 참
print(True or True) # True
print(True or False) # True
print(False or True) # True
print(False or False) # False
실용 예시
# 할인 대상 확인
age = int(input("나이: "))
is_student = input("학생인가요? (y/n): ")
if age < 18 or age >= 65 or is_student == "y":
print("할인 대상입니다")
else:
print("정가입니다")
# 휴일 확인
day = input("요일: ")
if day == "토요일" or day == "일요일":
print("주말입니다")
else:
print("평일입니다")
여러 값 중 하나인지 확인
# 계절 확인
month = int(input("월: "))
if month == 12 or month == 1 or month == 2:
print("겨울입니다")
elif month == 3 or month == 4 or month == 5:
print("봄입니다")
elif month == 6 or month == 7 or month == 8:
print("여름입니다")
else:
print("가을입니다")
🚫 not 연산자 - “아니다”
not의 특징
조건의 결과를 반대로 바꿈
print(not True) # False
print(not False) # True
실용 예시
# 로그아웃 상태 확인
is_logged_in = False
if not is_logged_in:
print("로그인이 필요합니다")
else:
print("이미 로그인되어 있습니다")
# 주말이 아닌 날 확인
day = input("요일: ")
if not (day == "토요일" or day == "일요일"):
print("평일입니다. 열심히 일해요!")
else:
print("주말입니다. 휴식하세요!")
부정 조건 활용
# 비밀번호 불일치 확인
password = input("비밀번호: ")
correct_password = "python123"
if not (password == correct_password):
print("비밀번호가 틀렸습니다")
else:
print("비밀번호가 맞습니다")
🎭 논리 연산자 조합
and와 or 함께 사용
# 학점 계산 (출석률과 점수 모두 고려)
attendance = int(input("출석률(%): "))
score = int(input("점수: "))
if (attendance >= 80 and score >= 90) or score >= 95:
print("A학점")
elif attendance >= 70 and score >= 80:
print("B학점")
elif attendance >= 60 and score >= 70:
print("C학점")
else:
print("F학점")
괄호로 우선순위 명확히 하기
# 놀이공원 입장 조건
age = int(input("나이: "))
height = int(input("키(cm): "))
has_guardian = input("보호자 동반? (y/n): ")
# 복잡한 조건을 괄호로 명확히 구분
if (age >= 12 and height >= 140) or (age < 12 and has_guardian == "y"):
print("입장 가능합니다")
else:
print("입장 불가능합니다")
📊 논리 연산자 우선순위
우선순위 순서
not
(가장 높음)and
or
(가장 낮음)
# 우선순위 예시
result = True or False and False
print(result) # True
# 위 코드는 다음과 같이 계산됨:
# True or (False and False)
# True or False
# True
명확한 코드를 위한 괄호 사용
# 괄호 없이 (헷갈림)
if age >= 18 and has_license or age >= 16 and has_guardian:
print("운전 가능")
# 괄호 사용 (명확함)
if (age >= 18 and has_license) or (age >= 16 and has_guardian):
print("운전 가능")
🎯 in 연산자 - 멤버십 테스트
in 연산자 기본 사용법
# 문자열에서 문자 찾기
word = "python"
if "y" in word:
print("y가 포함되어 있습니다")
# 여러 값 중 하나인지 확인
day = input("요일: ")
if day in ["토요일", "일요일"]:
print("주말입니다")
# 숫자 범위 확인
number = int(input("숫자: "))
if number in [1, 3, 5, 7, 9]:
print("1부터 9까지의 홀수입니다")
not in 연산자
# 금지된 단어 확인
comment = input("댓글: ")
banned_words = ["욕설", "비방", "광고"]
if comment not in banned_words:
print("댓글이 등록되었습니다")
else:
print("적절하지 않은 댓글입니다")
💡 실용적인 예시들
예시 1: 성적 등급 계산기
korean = int(input("국어 점수: "))
english = int(input("영어 점수: "))
math = int(input("수학 점수: "))
average = (korean + english + math) / 3
if average >= 90 and korean >= 80 and english >= 80 and math >= 80:
print("A등급")
elif average >= 80 and korean >= 70 and english >= 70 and math >= 70:
print("B등급")
elif average >= 70:
print("C등급")
else:
print("D등급")
print(f"평균: {average:.1f}점")
예시 2: 사용자 권한 체크
username = input("사용자명: ")
role = input("역할 (admin/user): ")
is_active = input("활성 상태? (y/n): ")
if (username == "admin" or role == "admin") and is_active == "y":
print("모든 기능에 접근 가능합니다")
elif role == "user" and is_active == "y":
print("일반 기능에 접근 가능합니다")
else:
print("접근이 제한되었습니다")
예시 3: 할인 계산기
price = int(input("상품 가격: "))
is_member = input("회원인가요? (y/n): ")
quantity = int(input("구매 수량: "))
discount = 0
if is_member == "y" and price >= 100000:
discount = 0.2 # 회원 + 10만원 이상: 20% 할인
elif is_member == "y" or price >= 50000:
discount = 0.1 # 회원 또는 5만원 이상: 10% 할인
elif quantity >= 5:
discount = 0.05 # 5개 이상: 5% 할인
final_price = price * (1 - discount)
print(f"최종 가격: {final_price:,.0f}원")
🚨 자주 발생하는 오류
오류 1: 조건 범위 실수
# ❌ 틀린 예
age = 25
if 18 <= age <= 65: # 이건 파이썬에서는 가능하지만...
print("성인")
# 더 명확한 방법
if age >= 18 and age <= 65:
print("성인")
오류 2: 논리 연산자 혼동
# ❌ 틀린 예 (항상 True)
age = 20
if age == 18 or 19 or 20: # 잘못된 사용!
print("해당 나이")
# ✅ 올바른 예
if age == 18 or age == 19 or age == 20:
print("해당 나이")
# 또는 in 사용
if age in [18, 19, 20]:
print("해당 나이")
오류 3: 우선순위 혼동
# ❌ 헷갈리는 코드
if True or False and False:
print("실행됨") # True가 출력됨
# ✅ 명확한 코드
if (True or False) and False:
print("실행 안됨") # 실행되지 않음
💡 퀴즈: 논리 연산자 이해도 체크
Q1. 다음 결과는?
print(True and False or True)
- True
- False
- 오류 발생
- None
💡 정답 확인
정답: 1번 (True)
계산 순서: True and False
→ False
, False or True
→ True
Q2. 다음 중 주말을 올바르게 확인하는 코드는?
if day == "토요일" or "일요일":
if day == "토요일" or day == "일요일":
if day == ("토요일" or "일요일"):
if day and "토요일" or "일요일":
💡 정답 확인
정답: 2번
각 조건을 완전히 작성해야 합니다. 1번은 항상 True가 되는 잘못된 코드입니다.
Q3. not
연산자의 역할은?
- 조건을 무시한다
- 조건을 반복한다
- 조건을 반대로 만든다
- 조건을 강화한다
💡 정답 확인
정답: 3번
not
연산자는 True를 False로, False를 True로 바꿉니다.
✅ 논리 연산자 마스터 체크리스트
✅ 논리 연산자 마스터 체크리스트
🚀 다음 단계
논리 연산자를 익혔으니, 이제 반복문을 배워서 같은 작업을 여러 번 수행하는 방법을 알아보겠습니다!
다음 토픽에서는:
- while 반복문: 조건이 참인 동안 계속 반복
- 반복 제어: break와 continue 활용
- 무한루프 방지: 안전한 반복문 작성법
프로그램이 지루한 반복 작업을 자동으로 처리할 수 있게 됩니다! ⚡
Last updated on