2단원 과제 정답: 연산자와 조건문¶
문제 1. 연산자 우선순위¶
① 512
② 64
③ 11
④ 2
⑤ 10
해설
| 항목 | 식 | 계산 과정 | 결과 |
|---|---|---|---|
| ① | 2 ** 3 ** 2 |
2 ** (3 ** 2) = 2 ** 9 |
512 |
| ② | (2 ** 3) ** 2 |
8 ** 2 |
64 |
| ③ | 3 + 4 * 2 |
3 + 8 |
11 |
| ④ | 10 % 3 + 1 |
1 + 1 |
2 |
| ⑤ | 10 // 3 * 3 + 10 % 3 |
3 * 3 + 1 |
10 |
①② 핵심 함정: **는 오른쪽부터 계산합니다. 2 ** 3 ** 2 ≠ (2 ** 3) ** 2
⑤ 핵심 함정: 10 // 3 * 3 + 10 % 3 = 9 + 1 = 10 (원래 수 복원 가능)
문제 2. 논리 연산자 우선순위¶
① True
② True
③ True
④ True
해설
논리 연산자 우선순위: not > and > or
| 항목 | 원본 | 계산 과정 | 결과 |
|---|---|---|---|
| ① | True and False or True |
(True and False) or True = False or True |
True |
| ② | not True or not False |
(not True) or (not False) = False or True |
True |
| ③ | True and not False |
True and (not False) = True and True |
True |
| ④ | not (True and False) |
not False |
True |
① 핵심 함정: or가 마지막에 계산되므로 and 결과(False)와 True의 or 연산이 됩니다.
문제 3. 같은 값, 다른 타입¶
① True
② True
③ False
④ <class 'bool'>
해설
| 항목 | 식 | 결과 | 이유 |
|---|---|---|---|
| ① | 5 == 5.0 |
True |
==은 값을 비교, 5과 5.0은 같은 값 |
| ② | 5 != "5" |
True |
int와 str은 다른 값 |
| ③ | type(5) == type(5.0) |
False |
int ≠ float, 타입이 다름 |
| ④ | type(5 == 5.0) |
<class 'bool'> |
비교 연산 결과는 항상 bool |
①③ 비교가 핵심 함정: 값은 같아도(True) 타입은 다릅니다(False).
④ 핵심 함정: 5 == 5.0의 결과는 True이며, type(True)는 bool입니다.
문제 4. if vs elif¶
① C
해설
score = 85
if 85 >= 90 → False (result = "F", 변화 없음)
if 85 >= 80 → True (result = "B")
if 85 >= 70 → True (result = "C") ← 덮어쓰기!
if 85 >= 60 → True (result = "D") ← 또 덮어쓰기!
모든 if가 독립적으로 실행되므로, 마지막으로 참이 된 조건의 값이 최종 결과가 됩니다.
elif였다면 처음 참이 된 80에서 "B"로 끝났을 것입니다.
문제 5. 학점 판별기¶
score = int(input("Score: "))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print("Grade:", grade)
if score % 2 == 0:
print(score, "is even")
else:
print(score, "is odd")
빈칸 정답
| 빈칸 | 정답 | 이유 |
|---|---|---|
score >= ______ |
80 |
80점 이상 90점 미만은 B |
score >= ______ |
70 |
70점 이상 80점 미만은 C |
______: |
else |
나머지는 F |
score ______ 2 |
% |
% 2 == 0이면 짝수 |
______: |
else |
나머지(홀수) 처리 |