반응형
불린 자료형이란 무엇인가?
불린(Boolean) 자료형은 프로그래밍에서 논리값을 표현하는 기본 자료형입니다. 오직 두 가지 값만을 가질 수 있습니다:
값 의미 설명
True | 참 | 조건이 성립하거나 값이 존재함을 의미 |
False | 거짓 | 조건이 성립하지 않거나 값이 없음을 의미 |
중요한 주의사항: True와 False는 파이썬의 예약어이므로 반드시 첫 글자를 대문자로 써야 합니다. true나 false로 쓰면 오류가 발생합니다.
불린 자료형의 기본 사용법
변수에 불린 값 할당하기
# 불린 값을 변수에 저장
is_sunny = True # 날씨가 맑다
is_raining = False # 비가 오지 않는다
# 자료형 확인
print(type(is_sunny)) # 출력: <class 'bool'>
print(type(is_raining)) # 출력: <class 'bool'>
# 불린 값 출력
print("오늘 날씨가 맑나요?", is_sunny) # 출력: 오늘 날씨가 맑나요? True
print("비가 오고 있나요?", is_raining) # 출력: 비가 오고 있나요? False
비교 연산자와 불린 자료형
비교 연산은 항상 불린 값을 반환합니다:
# 숫자 비교
print(5 == 5) # 출력: True (5와 5는 같다)
print(3 > 7) # 출력: False (3은 7보다 크지 않다)
print(10 >= 8) # 출력: True (10은 8보다 크거나 같다)
print(4 != 9) # 출력: True (4와 9는 다르다)
# 문자열 비교
print("apple" == "apple") # 출력: True
print("cat" < "dog") # 출력: True (알파벳 순서)
print("Python" != "Java") # 출력: True
자료형의 참과 거짓 판별
파이썬의 모든 자료형은 불린 맥락에서 참 또는 거짓으로 평가됩니다:
자료형 참(True)인 경우 거짓(False)인 경우
문자열 | "안녕하세요", "Python" | "" (빈 문자열) |
리스트 | [1, 2, 3], ["a", "b"] | [] (빈 리스트) |
튜플 | (1, 2), ("x", "y") | () (빈 튜플) |
딕셔너리 | {"name": "김철수"} | {} (빈 딕셔너리) |
집합 | {1, 2, 3} | set() (빈 집합) |
숫자 | 1, -5, 3.14, 100 | 0, 0.0 |
특수값 | 모든 객체 | None |
bool() 함수로 참/거짓 확인하기
# 문자열의 참/거짓
print(bool("파이썬")) # 출력: True
print(bool("")) # 출력: False
# 리스트의 참/거짓
print(bool([1, 2, 3])) # 출력: True
print(bool([])) # 출력: False
# 숫자의 참/거짓
print(bool(42)) # 출력: True
print(bool(0)) # 출력: False
print(bool(-5)) # 출력: True
# 딕셔너리의 참/거짓
print(bool({"이름": "홍길동"})) # 출력: True
print(bool({})) # 출력: False
# None의 참/거짓
print(bool(None)) # 출력: False
논리 연산자 활용하기
and, or, not 연산자
# and 연산자 (둘 다 참일 때만 True)
print(True and True) # 출력: True
print(True and False) # 출력: False
print(False and True) # 출력: False
print(False and False) # 출력: False
# or 연산자 (하나라도 참이면 True)
print(True or True) # 출력: True
print(True or False) # 출력: True
print(False or True) # 출력: True
print(False or False) # 출력: False
# not 연산자 (참/거짓을 뒤바꿈)
print(not True) # 출력: False
print(not False) # 출력: True
실제 상황에서의 논리 연산
# 학생 성적 관리 시스템
score = 85
attendance = 90
# 합격 조건: 성적 80점 이상이고 출석률 80% 이상
is_passed = (score >= 80) and (attendance >= 80)
print(f"합격 여부: {is_passed}") # 출력: 합격 여부: True
# 재시험 대상: 성적이 60점 미만이거나 출석률이 70% 미만
needs_retest = (score < 60) or (attendance < 70)
print(f"재시험 필요: {needs_retest}") # 출력: 재시험 필요: False
# 우수학생: 성적이 90점 이상이 아니다 (부정)
is_not_excellent = not (score >= 90)
print(f"우수학생이 아님: {is_not_excellent}") # 출력: 우수학생이 아님: True
조건문에서의 불린 활용
기본 if 문 활용
# 날씨에 따른 옷차림 추천 시스템
temperature = 25
is_raining = False
is_sunny = True
print("=== 오늘의 옷차림 추천 ===")
if temperature > 30:
print("반팔과 반바지를 입으세요.")
elif temperature > 20:
print("긴팔 셔츠가 적당합니다.")
else:
print("따뜻한 옷을 입으세요.")
if is_raining:
print("우산을 챙기세요!")
else:
print("우산은 필요 없습니다.")
if is_sunny:
print("선글라스를 착용하세요.")
자료형의 참/거짓을 이용한 조건문
# 사용자 입력 검증 시스템
user_name = input("이름을 입력하세요: ")
user_age = input("나이를 입력하세요: ")
# 빈 문자열은 False로 평가됨
if user_name: # user_name이 비어있지 않으면 True
print(f"안녕하세요, {user_name}님!")
else:
print("이름을 입력해주세요.")
if user_age:
try:
age = int(user_age)
if age >= 18:
print("성인입니다.")
else:
print("미성년자입니다.")
except ValueError:
print("올바른 숫자를 입력해주세요.")
else:
print("나이를 입력해주세요.")
반복문에서의 불린 활용
while 문과 불린
# 간단한 수 맞추기 게임
import random
# 1부터 10 사이의 랜덤한 숫자 생성
secret_number = random.randint(1, 10)
attempts = 0
max_attempts = 3
print("=== 숫자 맞추기 게임 ===")
print("1부터 10 사이의 숫자를 맞춰보세요!")
print(f"기회는 {max_attempts}번입니다.")
while attempts < max_attempts:
try:
guess = int(input(f"시도 {attempts + 1}: 숫자를 입력하세요: "))
attempts += 1
if guess == secret_number:
print(f"정답입니다! {attempts}번 만에 맞추셨네요!")
break
elif guess < secret_number:
print("더 큰 숫자입니다.")
else:
print("더 작은 숫자입니다.")
if attempts == max_attempts:
print(f"게임 종료! 정답은 {secret_number}였습니다.")
except ValueError:
print("올바른 숫자를 입력해주세요.")
attempts -= 1 # 잘못된 입력은 기회에서 제외
리스트와 불린을 이용한 데이터 처리
# 학생 성적 관리 시스템
students = [
{"이름": "김철수", "점수": 85, "출석": True},
{"이름": "이영희", "점수": 92, "출석": True},
{"이름": "박민수", "점수": 78, "출석": False},
{"이름": "최수정", "점수": 95, "출석": True},
{"이름": "장호현", "점수": 67, "출석": True}
]
print("=== 학생 성적 분석 ===")
# 모든 학생 정보를 처리
for student in students:
name = student["이름"]
score = student["점수"]
attendance = student["출석"]
# 합격 조건: 점수 80점 이상이고 출석
is_passed = (score >= 80) and attendance
# 우수학생: 점수 90점 이상이고 출석
is_excellent = (score >= 90) and attendance
print(f"{name}: {score}점, 출석({attendance})")
if is_excellent:
print(" → 우수학생입니다! 🏆")
elif is_passed:
print(" → 합격입니다! ✅")
else:
if not attendance:
print(" → 출석 부족으로 불합격 ❌")
else:
print(" → 점수 부족으로 불합격 ❌")
print()
# 통계 계산
total_students = len(students)
passed_students = sum(1 for s in students if (s["점수"] >= 80) and s["출석"])
excellent_students = sum(1 for s in students if (s["점수"] >= 90) and s["출석"])
print("=== 통계 ===")
print(f"전체 학생 수: {total_students}명")
print(f"합격자 수: {passed_students}명 ({passed_students/total_students*100:.1f}%)")
print(f"우수학생 수: {excellent_students}명 ({excellent_students/total_students*100:.1f}%)")
고급 불린 활용 - 텍스트 어드벤처 게임
# 텍스트 기반 어드벤처 게임
import random
class Player:
def __init__(self, name):
self.name = name
self.health = 100
self.has_sword = False
self.has_key = False
self.has_treasure = False
def is_alive(self):
"""플레이어가 살아있는지 확인"""
return self.health > 0
def can_fight(self):
"""전투 가능 여부 확인"""
return self.is_alive() and self.has_sword
def can_open_door(self):
"""문을 열 수 있는지 확인"""
return self.has_key
def is_winner(self):
"""게임에서 승리했는지 확인"""
return self.has_treasure and self.is_alive()
def play_adventure_game():
print("=== 보물 찾기 어드벤처 ===")
player_name = input("당신의 이름을 입력하세요: ")
# 이름이 비어있으면 기본 이름 사용
if not player_name: # 빈 문자열은 False
player_name = "모험가"
player = Player(player_name)
print(f"\n안녕하세요, {player.name}님! 모험을 시작합니다.")
# 게임 메인 루프
while player.is_alive() and not player.is_winner():
print(f"\n현재 상태: HP {player.health}")
print("1. 숲 탐험")
print("2. 동굴 입구")
print("3. 상태 확인")
print("4. 게임 종료")
choice = input("선택하세요 (1-4): ")
if choice == "1":
explore_forest(player)
elif choice == "2":
enter_cave(player)
elif choice == "3":
show_status(player)
elif choice == "4":
print("게임을 종료합니다.")
break
else:
print("올바른 선택을 입력해주세요.")
# 게임 결과 출력
if player.is_winner():
print(f"\n🎉 축하합니다! {player.name}님이 보물을 찾아 승리했습니다!")
elif not player.is_alive():
print(f"\n💀 {player.name}님이 쓰러졌습니다. 게임 오버!")
def explore_forest(player):
"""숲 탐험 함수"""
print("\n🌲 숲을 탐험합니다...")
# 랜덤 이벤트 발생
event = random.randint(1, 3)
if event == 1:
print("반짝이는 검을 발견했습니다!")
if not player.has_sword: # 검이 없을 때만
player.has_sword = True
print("검을 획득했습니다! 이제 몬스터와 싸울 수 있습니다.")
else:
print("이미 검을 가지고 있습니다.")
elif event == 2:
print("야생 늑대가 나타났습니다!")
if player.can_fight(): # 검이 있고 살아있으면
fight_result = random.choice([True, False])
if fight_result:
print("늑대를 물리쳤습니다!")
else:
print("늑대에게 공격당했습니다!")
player.health -= 30
else:
print("무기가 없어서 도망쳤습니다!")
player.health -= 20
else:
print("아무것도 찾지 못했습니다.")
def enter_cave(player):
"""동굴 입구 함수"""
print("\n🕳️ 동굴 입구에 도착했습니다...")
if not player.has_key:
print("열쇠가 없어서 문이 열리지 않습니다.")
print("숲에서 열쇠를 찾아보세요!")
# 가끔 열쇠를 발견할 수 있음
if random.randint(1, 3) == 1:
print("잠깐! 문 앞에서 열쇠를 발견했습니다!")
player.has_key = True
if player.can_open_door(): # 열쇠가 있으면
print("문을 열고 동굴에 들어갑니다...")
# 보물 발견 확률
treasure_found = random.choice([True, False])
if treasure_found:
print("🏆 보물 상자를 발견했습니다!")
player.has_treasure = True
else:
print("동굴이 비어있습니다...")
# 가끔 몬스터 등장
if random.randint(1, 2) == 1:
print("동굴 안에서 박쥐 떼가 공격합니다!")
player.health -= 15
def show_status(player):
"""플레이어 상태 출력"""
print(f"\n=== {player.name}의 상태 ===")
print(f"체력: {player.health}/100")
print(f"검 보유: {'✅' if player.has_sword else '❌'}")
print(f"열쇠 보유: {'✅' if player.has_key else '❌'}")
print(f"보물 보유: {'✅' if player.has_treasure else '❌'}")
# 상태에 따른 조언
if not player.is_alive():
print("⚠️ 위험! 체력이 부족합니다!")
elif player.can_fight() and player.can_open_door():
print("💪 모든 준비가 완료되었습니다!")
elif not player.has_sword:
print("💡 팁: 숲에서 검을 찾아보세요.")
elif not player.has_key:
print("💡 팁: 동굴 문을 열 열쇠가 필요합니다.")
# 게임 실행
if __name__ == "__main__":
play_adventure_game()
불린 자료형 활용 팁
1. 플래그 변수 활용
# 프로그램 상태를 관리하는 플래그 변수들
is_logged_in = False # 로그인 상태
is_admin = False # 관리자 권한
has_permission = False # 접근 권한
is_debug_mode = True # 디버그 모드
# 상태에 따른 동작 제어
if is_logged_in and has_permission:
print("데이터에 접근할 수 있습니다.")
elif is_logged_in:
print("권한이 부족합니다.")
else:
print("먼저 로그인해주세요.")
if is_debug_mode:
print("디버그 정보: 현재 사용자 상태 확인됨")
2. 조건 체이닝
# 여러 조건을 연결하여 복잡한 로직 구현
age = 25
has_license = True
has_car = True
has_insurance = False
# 운전 가능 여부 판단
can_drive = (
age >= 18 and # 성인이고
has_license and # 면허가 있고
has_car and # 차가 있고
has_insurance # 보험이 있어야 함
)
print(f"운전 가능 여부: {can_drive}")
# 각 조건별 안내 메시지
if not (age >= 18):
print("18세 이상이어야 합니다.")
elif not has_license:
print("운전면허증이 필요합니다.")
elif not has_car:
print("차량이 필요합니다.")
elif not has_insurance:
print("자동차 보험이 필요합니다.")
else:
print("모든 조건을 만족합니다!")
마무리
불린 자료형은 파이썬 프로그래밍의 핵심 요소입니다. 조건문, 반복문, 논리 연산 등 프로그램의 흐름을 제어하는 모든 곳에서 사용됩니다.
핵심 포인트:
- True와 False는 대소문자를 정확히 지켜야 함
- 모든 자료형은 불린 맥락에서 참/거짓으로 평가됨
- 빈 컨테이너([], {}, "")와 0, None은 거짓으로 평가됨
- 논리 연산자(and, or, not)를 활용하여 복잡한 조건 구현 가능
- 플래그 변수를 통해 프로그램 상태를 효과적으로 관리 가능
이러한 불린 자료형의 특성을 잘 이해하고 활용하면, 더욱 논리적이고 효율적인 파이썬 프로그램을 작성할 수 있습니다.
반응형
'파이썬' 카테고리의 다른 글
9. 파이썬 조건문 (IF문) 완벽히 이해하기. 예제로 배우는 코딩공부. (0) | 2025.05.27 |
---|---|
8. 파이썬 변수와 메모리 관리 완벽 가이드 (0) | 2025.05.26 |
6. 파이썬 집합(SET) 자료형. 여러 예제로 깊게 이해하기. (0) | 2025.05.25 |
5. 파이썬 딕셔너리 초보부터 중수까지 완벽한 예제로 공부하자. (0) | 2025.05.25 |
4. 파이썬 튜플 기초부터 고급 활용까지 (0) | 2025.05.23 |