Python의 조건문(if), 반복문(for, while), 그리고 관련 문법에 대한 상세한 설명과 예제를 제공합니다.
- 조건식의 결과는 항상 True 또는 False
- 각 블록은 반드시 동일한 **인덴트(들여쓰기)**로 작성
- Python은 중괄호
{}대신 콜론:과 들여쓰기로 블록 구분
조건이 참일 때만 실행됩니다.
if 조건식:
# 참일 때 수행할 구문 블록예제:
age = 20
if age >= 18:
print("성인입니다.")
# 출력결과: 성인입니다.
score = 85
if score >= 60:
print("합격입니다!")
print("축하합니다!")
# 출력결과:
# 합격입니다!
# 축하합니다!조건이 참일 때와 거짓일 때 각각 다른 코드를 실행합니다.
if 조건식:
# 참일 때 수행할 구문 블록
else:
# 거짓일 때 수행할 구문 블록예제:
age = 15
if age >= 18:
print("성인입니다.")
else:
print("미성년자입니다.")
# 출력결과: 미성년자입니다.
number = 7
if number % 2 == 0:
print(f"{number}은(는) 짝수입니다.")
else:
print(f"{number}은(는) 홀수입니다.")
# 출력결과: 7은(는) 홀수입니다.여러 조건을 순차적으로 검사합니다.
if 조건식1:
# 조건식1이 참일 때 수행할 구문 블록
elif 조건식2:
# 조건식2가 참일 때 수행할 구문 블록
elif 조건식3:
# 조건식3이 참일 때 수행할 구문 블록
else:
# 모든 조건이 거짓일 때 수행할 구문 블록예제:
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"점수: {score}, 학점: {grade}")
# 출력결과: 점수: 85, 학점: B주의: elif는 위에서부터 순차적으로 검사하므로 조건 순서가 중요합니다.
# 잘못된 예시 - 조건 순서 문제
score = 95
if score >= 60:
print("D학점") # 이것이 먼저 실행됨!
elif score >= 70:
print("C학점")
elif score >= 80:
print("B학점")
elif score >= 90:
print("A학점")
# 출력결과: D학점 (의도하지 않은 결과!)age = 25
has_id = True
if age >= 18:
if has_id:
print("입장 가능합니다.")
else:
print("신분증이 필요합니다.")
else:
print("미성년자는 입장 불가합니다.")
# 출력결과: 입장 가능합니다.| 연산자 | 설명 | 예제 | 결과 |
|---|---|---|---|
== |
같다 | 5 == 5 |
True |
!= |
다르다 | 5 != 3 |
True |
> |
크다 | 5 > 3 |
True |
< |
작다 | 3 < 5 |
True |
>= |
크거나 같다 | 5 >= 5 |
True |
<= |
작거나 같다 | 3 <= 5 |
True |
a = 10
b = 20
print(a == b) # False
print(a != b) # True
print(a > b) # False
print(a < b) # True
print(a >= 10) # True
print(b <= 20) # True| 연산자 | 설명 | 예제 | 결과 |
|---|---|---|---|
and |
두 조건 모두 참 | True and True |
True |
or |
하나라도 참 | True or False |
True |
not |
부정 (참↔거짓) | not True |
False |
# and - 둘 다 참이어야 참
print(True and True) # True
print(True and False) # False
print(False and True) # False
print(False and False) # False
# or - 하나라도 참이면 참
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실전 예제:
age = 25
has_license = True
# and 사용
if age >= 18 and has_license:
print("운전 가능합니다.")
# 출력결과: 운전 가능합니다.
# or 사용
is_student = False
is_senior = True
if is_student or is_senior:
print("할인 적용됩니다.")
# 출력결과: 할인 적용됩니다.
# not 사용
is_holiday = False
if not is_holiday:
print("출근해야 합니다.")
# 출력결과: 출근해야 합니다.Python은 비교 연산자를 연결(chaining)할 수 있습니다.
score = 70
# 일반적인 방법
if score >= 0 and score <= 100:
print("유효한 점수")
# Python Chaining (권장)
if 0 <= score <= 100:
print("유효한 점수")
# 출력결과: 유효한 점수
# 여러 비교 연결
x = 5
print(1 < x < 10) # True (1 < x and x < 10)
print(1 < x < 3) # False
print(1 < x <= 5 < 10) # True주의: Python Chaining vs 다른 언어
# Python에서의 해석
False == True == False
# 해석: (False == True) and (True == False)
# = False and False = False
# 다른 언어에서는 다르게 동작할 수 있음
# (False == True) == False
# = False == False = True두 조건이 다를 때 참을 반환합니다.
# XOR - 다르면 참, 같으면 거짓
print(True ^ True) # False
print(True ^ False) # True
print(False ^ True) # True
print(False ^ False) # False
# 실전 예제
a = 5
b = 3
# 둘 중 하나만 짝수인지 확인
is_a_even = (a % 2 == 0)
is_b_even = (b % 2 == 0)
if is_a_even ^ is_b_even:
print("둘 중 하나만 짝수입니다.")
else:
print("둘 다 짝수이거나 둘 다 홀수입니다.")
# 출력결과: 둘 다 짝수이거나 둘 다 홀수입니다.Python에서 다양한 값의 참/거짓 판정 규칙입니다.
| 타입 | 참 (True) | 거짓 (False) |
|---|---|---|
bool |
True |
False |
int, float |
0이 아닌 숫자 | 0, 0.0 |
str |
문자가 있는 문자열 | "" (빈 문자열) |
list |
요소가 있는 리스트 | [] (빈 리스트) |
tuple |
요소가 있는 튜플 | () (빈 튜플) |
dict |
항목이 있는 딕셔너리 | {} (빈 딕셔너리) |
set |
요소가 있는 셋 | set() (빈 셋) |
None |
- | 항상 거짓 |
# 다양한 타입의 참/거짓 테스트
test_values = [
0, 0.0, "", [], (), {}, set(), None, # False
1, -1, 0.1, "hello", [0], (0,), {"a": 1} # True
]
for val in test_values:
result = "참" if val else "거짓"
print(f"{repr(val):15} -> {result}")
# 실전 활용
data = []
if data:
print("데이터가 있습니다.")
else:
print("데이터가 없습니다.")
# 출력결과: 데이터가 없습니다.
name = ""
if not name:
print("이름을 입력해주세요.")
# 출력결과: 이름을 입력해주세요.and/or 연산자는 결과가 확정되면 나머지를 평가하지 않습니다.
# and: 왼쪽이 거짓이면 오른쪽 평가 안 함
print(False and print("실행됨")) # False (print 실행 안 됨)
# or: 왼쪽이 참이면 오른쪽 평가 안 함
print(True or print("실행됨")) # True (print 실행 안 됨)중요: and/or의 반환값
and/or은 True/False가 아닌 실제 값을 반환합니다.
# or: 왼쪽이 참이면 왼쪽 반환, 거짓이면 오른쪽 반환
result = 0 or 100
print(result) # 100 (왼쪽이 거짓)
result = 120 or 0
print(result) # 120 (왼쪽이 참)
# and: 왼쪽이 참이면 오른쪽 반환, 거짓이면 왼쪽 반환
result = 100 and 200
print(result) # 200 (왼쪽이 참)
result = 0 and 200
print(result) # 0 (왼쪽이 거짓)SCE 활용 예제:
# 조건부 실행
n = 10
(n % 5 == 0) and print(f"{n}은(는) 5의 배수")
# 출력결과: 10은(는) 5의 배수
n = 9
(n % 5 == 0) or print(f"{n}은(는) 5의 배수가 아님")
# 출력결과: 9은(는) 5의 배수가 아님
# 기본값 설정
name = ""
display_name = name or "익명"
print(display_name) # 익명
name = "홍길동"
display_name = name or "익명"
print(display_name) # 홍길동Python의 삼항 연산자(Conditional Expression)는 한 줄로 조건문을 작성합니다.
(참일 때의 값) if (조건식) else (거짓일 때의 값)n = 10
result = "양수" if n > 0 else "음수 또는 0"
print(result)
# 출력결과: 양수
age = 15
status = "성인" if age >= 18 else "미성년자"
print(status)
# 출력결과: 미성년자
# 변수에 할당하지 않고 직접 사용
print("짝수" if 10 % 2 == 0 else "홀수")
# 출력결과: 짝수# 두 숫자 중 큰 값
a = 72
b = 54
max_val = a if a > b else b
print(f"더 큰 값: {max_val}")
# 출력결과: 더 큰 값: 72
# 두 숫자의 차 (절댓값)
diff = (a - b) if (a > b) else (b - a)
print(f"두 수의 차: {diff}")
# 출력결과: 두 수의 차: 18
# 리스트가 비어있는지 확인
items = [1, 2, 3]
message = "비어있지 않음" if items else "비어있음"
print(message)
# 출력결과: 비어있지 않음
# 중첩 삼항 연산자 (가독성 주의)
score = 85
grade = "A" if score >= 90 else ("B" if score >= 80 else ("C" if score >= 70 else "F"))
print(grade)
# 출력결과: B# if-else 문
if n > 0:
result = "양수"
else:
result = "음수 또는 0"
# 삼항 연산자 (동일한 결과)
result = "양수" if n > 0 else "음수 또는 0"
# 삼항 연산자가 적합한 경우: 간단한 값 할당
# if-else가 적합한 경우: 복잡한 로직, 여러 문장 실행for 변수 in iterable객체:
수행문 1
수행문 2
else:
# 순환문을 정상적으로 완료했을 때 수행 (선택사항)Iterable 객체: range, str, list, tuple, set, dict 등
숫자 범위의 iterable 객체를 생성합니다.
# range(끝) - 0부터 끝-1까지
print(list(range(5)))
# [0, 1, 2, 3, 4]
# range(시작, 끝) - 시작부터 끝-1까지
print(list(range(3, 8)))
# [3, 4, 5, 6, 7]
# range(시작, 끝, 스텝)
print(list(range(0, 10, 2))) # [0, 2, 4, 6, 8]
print(list(range(10, 0, -1))) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
print(list(range(10, 0, -2))) # [10, 8, 6, 4, 2]# 리스트 순회
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# 출력결과:
# apple
# banana
# cherry
# range 순회
for i in range(5):
print(i, end=' ')
# 출력결과: 0 1 2 3 4
# 문자열 순회
for char in "Hello":
print(char, end='-')
# 출력결과: H-e-l-l-o-변수를 사용하지 않을 때는 _를 관례적으로 사용합니다.
# 5번 반복
for _ in range(5):
print("Hello")
# 횟수만 중요한 경우
total = 0
for _ in range(100):
total += 1
print(total) # 100인덱스와 값을 함께 얻을 수 있습니다.
animals = ["dog", "cat", "bird", "puppy", "kitty"]
# enumerate 기본 사용
for x in enumerate(animals):
print(x)
# (0, 'dog')
# (1, 'cat')
# (2, 'bird')
# (3, 'puppy')
# (4, 'kitty')
# 인덱스와 값 분리
for idx, animal in enumerate(animals):
print(f"{idx}: {animal}")
# 0: dog
# 1: cat
# 2: bird
# 3: puppy
# 4: kitty
# 시작 인덱스 지정
for idx, animal in enumerate(animals, start=1):
print(f"{idx}. {animal}")
# 1. dog
# 2. cat
# 3. bird
# 4. puppy
# 5. kitty여러 iterable 객체를 병렬로 순회합니다.
# 두 리스트 병렬 순회
numbers = [10, 20, 30]
letters = ["a", "b", "c"]
for num, letter in zip(numbers, letters):
print(f"{num} - {letter}")
# 10 - a
# 20 - b
# 30 - c
# 세 개 이상도 가능
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["Seoul", "Busan", "Daegu"]
for name, age, city in zip(names, ages, cities):
print(f"{name}({age}) - {city}")
# Alice(25) - Seoul
# Bob(30) - Busan
# Charlie(35) - Daegu
# 길이가 다른 경우 - 짧은 것에 맞춤
list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c']
print(list(zip(list1, list2)))
# [(1, 'a'), (2, 'b'), (3, 'c')]
# zip_longest 사용 (itertools)
from itertools import zip_longest
print(list(zip_longest(list1, list2, fillvalue='-')))
# [(1, 'a'), (2, 'b'), (3, 'c'), (4, '-'), (5, '-')]myDict = {"name": "hong", "age": 24, "grade": 4}
# 키 순회 (기본)
for key in myDict:
print(key)
# name
# age
# grade
# keys() 사용 (명시적)
for key in myDict.keys():
print(key)
# values() - 값만 순회
for value in myDict.values():
print(value)
# hong
# 24
# 4
# items() - 키-값 쌍 순회
for key, value in myDict.items():
print(f"{key}: {value}")
# name: hong
# age: 24
# grade: 4for 문이 break 없이 정상 완료되면 else 블록이 실행됩니다.
# break 없이 완료 - else 실행
for i in range(5):
print(i)
else:
print("반복 완료!")
# 0, 1, 2, 3, 4
# 반복 완료!
# break로 중단 - else 실행 안 됨
for i in range(5):
if i == 3:
break
print(i)
else:
print("반복 완료!")
# 0, 1, 2 (else 블록 실행 안 됨)
# 실전 예제: 소수 판별
num = 17
for i in range(2, num):
if num % i == 0:
print(f"{num}은(는) 소수가 아닙니다.")
break
else:
print(f"{num}은(는) 소수입니다.")
# 17은(는) 소수입니다.리스트를 간결하게 생성하는 문법입니다.
기본 구문:
[표현식 for 항목 in iterable]
[표현식 for 항목 in iterable if 조건]기본 예제:
# 기본 사용
squares = [x**2 for x in range(5)]
print(squares)
# [0, 1, 4, 9, 16]
# 조건 추가
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)
# [0, 4, 16, 36, 64]
# 문자열 처리
words = ['hello', 'world', 'python']
upper_words = [w.upper() for w in words]
print(upper_words)
# ['HELLO', 'WORLD', 'PYTHON']
# 리스트 값 변환
numbers = [1, 2, 3, 4]
tripled = [num * 3 for num in numbers]
print(tripled)
# [3, 6, 9, 12]
# 조건부 추출
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_nums = [x for x in numbers if x % 2 == 0]
print(even_nums)
# [2, 4, 6, 8, 10]삼항 연산자와 함께:
# 조건에 따라 다른 값
numbers = [1, 2, 3, 4, 5]
result = ["짝수" if x % 2 == 0 else "홀수" for x in numbers]
print(result)
# ['홀수', '짝수', '홀수', '짝수', '홀수']
# 음수를 0으로 변환
values = [1, -2, 3, -4, 5]
non_negative = [x if x >= 0 else 0 for x in values]
print(non_negative)
# [1, 0, 3, 0, 5]중첩 루프:
# 2차원 리스트 평탄화
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 곱셈표
multiplication = [(i, j, i*j) for i in range(1, 4) for j in range(1, 4)]
print(multiplication)
# [(1, 1, 1), (1, 2, 2), (1, 3, 3), (2, 1, 2), (2, 2, 4), (2, 3, 6), (3, 1, 3), (3, 2, 6), (3, 3, 9)]딕셔너리를 간결하게 생성합니다.
기본 구문:
{키_표현식: 값_표현식 for 항목 in iterable}
{키_표현식: 값_표현식 for 항목 in iterable if 조건}예제:
# 기본 사용
squares = {x: x**2 for x in range(5)}
print(squares)
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 조건 추가
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares)
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
# 키-값 필터링
fruits = {"apple": "red", "banana": "yellow", "peach": "pink"}
filtered = {k: v for k, v in fruits.items() if k != "banana"}
print(filtered)
# {'apple': 'red', 'peach': 'pink'}
# 키-값 교환
original = {'a': 1, 'b': 2, 'c': 3}
swapped = {v: k for k, v in original.items()}
print(swapped)
# {1: 'a', 2: 'b', 3: 'c'}
# 두 리스트로 딕셔너리 생성
keys = ['name', 'age', 'city']
values = ['Alice', 25, 'Seoul']
person = {k: v for k, v in zip(keys, values)}
print(person)
# {'name': 'Alice', 'age': 25, 'city': 'Seoul'}셋을 간결하게 생성합니다.
기본 구문:
{표현식 for 항목 in iterable}
{표현식 for 항목 in iterable if 조건}예제:
# 기본 사용
squares = {x**2 for x in range(5)}
print(squares)
# {0, 1, 4, 9, 16}
# 중복 자동 제거
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique = {x for x in numbers}
print(unique)
# {1, 2, 3, 4}
# 나머지 연산으로 가능한 값들
remainders = {num % 3 for num in range(10)}
print(remainders)
# {0, 1, 2}
# 조건 추가
even_squares = {x**2 for x in range(10) if x % 2 == 0}
print(even_squares)
# {0, 4, 16, 36, 64}괄호 ()를 사용하면 Generator가 생성됩니다 (메모리 효율적).
# Generator Expression
gen = (x**2 for x in range(5))
print(gen)
# <generator object <genexpr> at 0x...>
# 값을 하나씩 가져옴
print(next(gen)) # 0
print(next(gen)) # 1
print(next(gen)) # 4
# for문으로 순회
gen = (x**2 for x in range(5))
for val in gen:
print(val, end=' ')
# 0 1 4 9 16
# sum, max 등과 함께 사용 (메모리 효율적)
total = sum(x**2 for x in range(1000000))
print(total)조건이 참인 동안 반복합니다.
while 조건식:
수행문1
수행문2예제:
count = 5
while count > 0:
print(count)
count -= 1
# 5, 4, 3, 2, 1
# 합계 계산
total = 0
num = 1
while num <= 10:
total += num
num += 1
print(f"1부터 10까지 합: {total}")
# 1부터 10까지 합: 55while 문이 break 없이 정상 종료되면 else 블록이 실행됩니다.
count = 3
while count > 0:
print(count)
count -= 1
else:
print("Done")
# 3, 2, 1, Done
# break 사용 시 else 실행 안 됨
count = 3
while count > 0:
if count == 2:
break
print(count)
count -= 1
else:
print("Done")
# 3 (Done 출력 안 됨)반복문을 즉시 종료합니다.
count = 5
while count > 0:
print(count)
if count == 3:
break
count -= 1
print("반복 종료")
# 5, 4, 3
# 반복 종료
# 무한 루프에서 탈출
while True:
user_input = input("종료하려면 'q'를 입력하세요: ")
if user_input == 'q':
print("프로그램 종료")
break
print(f"입력: {user_input}")현재 반복을 건너뛰고 다음 반복으로 이동합니다.
count = 5
while count > 0:
count -= 1
if count == 3:
continue # 3일 때 아래 print 건너뛰기
print(count)
# 4, 2, 1, 0 (3은 출력 안 됨)
# 짝수만 출력
num = 0
while num < 10:
num += 1
if num % 2 != 0:
continue
print(num, end=' ')
# 2 4 6 8 10| 키워드 | 동작 | 사용 시점 |
|---|---|---|
break |
반복문 완전히 종료 | 특정 조건에서 반복 탈출 |
continue |
현재 반복만 건너뛰기 | 특정 조건에서 처리 생략 |
# break 예제
for i in range(10):
if i == 5:
break
print(i, end=' ')
print("\n종료")
# 0 1 2 3 4
# 종료
# continue 예제
for i in range(10):
if i == 5:
continue
print(i, end=' ')
print("\n종료")
# 0 1 2 3 4 6 7 8 9
# 종료break는 가장 가까운 반복문만 종료합니다.
# 중첩 for문
for i in range(3):
for j in range(3):
if j == 1:
break # 안쪽 for문만 종료
print(f"({i}, {j})")
# (0, 0)
# (1, 0)
# (2, 0)
# 모든 반복문 탈출하기 - flag 사용
found = False
for i in range(3):
if found:
break
for j in range(3):
if i == 1 and j == 1:
found = True
break
print(f"({i}, {j})")
# (0, 0), (0, 1), (0, 2), (1, 0)pass는 아무 동작도 하지 않는 문장입니다. 빈 블록이 필요할 때 사용합니다.
# 조건문에서
a = 10
if a > 0:
pass # 나중에 구현
else:
print("0보다 작음")
# 함수 정의에서
def my_function():
pass # 나중에 구현
# 클래스 정의에서
class MyClass:
pass # 나중에 구현
# 반복문에서
for i in range(10):
pass # 나중에 구현
# 예외 처리에서
try:
# 위험한 코드
x = 1 / 0
except ZeroDivisionError:
pass # 무시하고 계속 진행| 키워드 | 위치 | 동작 |
|---|---|---|
pass |
어디서나 | 아무것도 하지 않음 |
continue |
반복문 내에서만 | 다음 반복으로 건너뜀 |
# pass - 아무것도 하지 않고 다음 줄 실행
for i in range(3):
if i == 1:
pass
print(i)
# 0, 1, 2 (모두 출력)
# continue - 다음 반복으로 건너뜀
for i in range(3):
if i == 1:
continue
print(i)
# 0, 2 (1은 출력 안 됨)Python 3에서는 ...도 pass처럼 사용할 수 있습니다.
def my_function():
... # pass와 동일
class MyClass:
... # pass와 동일| 유형 | 구문 | 설명 |
|---|---|---|
| 단일 조건 | if 조건: |
조건 참일 때 실행 |
| if-else | if 조건: ... else: |
참/거짓에 따라 분기 |
| if-elif-else | if ... elif ... else: |
다중 조건 |
| 삼항 연산자 | 값1 if 조건 else 값2 |
한 줄 조건문 |
| 유형 | 구문 | 설명 |
|---|---|---|
| for | for x in iterable: |
iterable 순회 |
| while | while 조건: |
조건 참인 동안 반복 |
| break | break |
반복문 종료 |
| continue | continue |
현재 반복 건너뛰기 |
| pass | pass |
빈 블록 자리 채움 |
| 유형 | 구문 | 결과 |
|---|---|---|
| List | [x for x in iterable] |
리스트 |
| Dict | {k: v for k, v in iterable} |
딕셔너리 |
| Set | {x for x in iterable} |
셋 |
| Generator | (x for x in iterable) |
제너레이터 |
| 함수 | 설명 | 예제 |
|---|---|---|
range() |
숫자 범위 생성 | range(5), range(1, 10, 2) |
enumerate() |
인덱스와 값 반환 | enumerate(list) |
zip() |
여러 iterable 병렬 순회 | zip(list1, list2) |