6단원 쪽지시험 정답: 예외 처리 & 파일 처리¶
문제 1. try / else / finally 흐름¶
① 값: 20.0
② 끝
③ ===
④ 에러
⑤ 끝
해설
process(5):
- 100 / 5 = 20.0 → 오류 없음 → else 실행 → 값: 20.0
- finally 항상 실행 → 끝
process(0):
- 100 / 0 → ZeroDivisionError → except 실행 → 에러
- else는 실행되지 않음 (예외가 발생했으므로)
- finally 항상 실행 → 끝
문제 2. 파일 모드 + 내용 예측¶
① 3
② A
③ B
④ C
해설
| 작업 | 모드 | 결과 |
|---|---|---|
첫 번째 with |
"w" |
"A\n", "B\n" 쓰기 |
두 번째 with |
"a" |
"C\n" 추가 |
세 번째 with |
"r" |
3줄 읽기 |
readlines() → ["A\n", "B\n", "C\n"] → len = 3
strip()으로 \n 제거 후 A, B, C 출력.
문제 3. raise + 다중 except¶
① OK: 33
② V: 음수 불가
③ V: invalid literal for int() with base 10: 'abc'
④ Z: 0 불가
해설
| 호출 | 흐름 | 출력 |
|---|---|---|
check("3") |
int("3")=3, 3≥0, 100//3=33 |
OK: 33 |
check("-1") |
int("-1")=-1, n<0 → raise ValueError |
V: 음수 불가 |
check("abc") |
int("abc") → ValueError (Python 기본 메시지) |
V: invalid literal... |
check("0") |
int("0")=0, 0≥0, 100//0 → ZeroDivisionError |
Z: 0 불가 |
③에서 raise가 아닌 Python 내장 ValueError가 발생하므로 Python 기본 오류 메시지가 출력됩니다.
문제 4. readlines + strip¶
① <class 'list'>
② 3
③ world
④ world
⑤ hello
python
해설
readlines() → ["hello\n", "world\n", "python\n"]
| 항목 | 식 | 결과 |
|---|---|---|
| ① | type(lines) |
<class 'list'> |
| ② | len(lines) |
3 |
| ③ | lines[1] |
"world\n" (print가 \n 포함 출력 → 빈 줄 생김) |
| ④ | lines[1].strip() |
"world" |
| ⑤ | lines[0] + lines[2] |
"hello\npython\n" → 두 줄 출력 |
③의 print(lines[1])은 "world\n"을 출력하므로 줄바꿈이 두 번 됩니다.
문제 5. FileNotFoundError + 루프¶
① Hello
② [b.txt 없음]
③ World
④ 총 3 개
해설
read_safe는 파일이 없으면 예외를 잡아 "[파일명 없음]" 문자열을 반환합니다.
리스트 컴프리헨션으로 세 파일을 모두 처리 → results = ["Hello", "[b.txt 없음]", "World"]
len(results) = 3