- if 조건문 활용
- continue :
- 해당 반복문을 빠져나와 다음 반복을 거침
- pass :
- 해당 반복문에 그대로 남아서 아래 있는 실행문을 모두 거친 후 다음 반복을 거침
cnt = 0
for i in range(1,11):
if i % 2 == 0:
pass
print(i)
cnt += 1
print(f"출력된 숫자 개수: {cnt}")
# 1 2 3 4 5 6 7 8 9 10 출력된 숫자 개수: 10
cnt = 0
for i in range(1,11):
if i % 2 == 0:
continue
print(i)
cnt += 1
print(f"출력된 숫자 개수: {cnt}")
# 1 3 5 7 9 출력된 숫자 개수: 5
- for 반복문
for 변수 in 반복가능한객체:
수행할 코드 블록
- 반복 가능한 객체: 리스트, 튜플, 문자열, range 객체 등
- range()
- 특정 범위의 정수 시퀀스 생성하는 함수
- ex) range(5): 0부터 4까지의 정수를 만들어줌
- ex) range(start, end, step): end는 끝값 포함x
- 반복문 제어문
- break: 현재 반복문을 즉시 종료함. 반복 조건이 아직 참이더라도 break를 만나는 순간 반복문을 빠져나옴
- continue: 현재 반복 순회를 건너뛰고 다음 반복으로 넘어감
for i in range(1, 11):
if i == 5:
break
print(i)
# 1
# 2
# 3
# 4
for i in range(1, 11):
if i == 5:
continue
print(i)
# 1
# 2
# 3
# 4
# 6
# 7
# 8
# 9
# 10
- enumerate()
- 인덱스와 값을 동시에 얻을 수 있음
fruits = "apple"
for idx, fruit_char in enumerate(fruits):
print(f"{idx}: {fruit_char}")
# 0: a
# 1: p
# 2: p
# 3: l
# 4: e
- zip()
- 여러 리스트를 병렬로 순회할 수 있음
fruits = ["apple", "banana", "cherry"]
prices = [1000, 2000, 3000]
for fruit, price in zip(fruits, prices):
print(f"{fruit}: {price}원")
# apple: 1000원
# banana: 2000원
# cherry: 3000원
- for-else 구문
- else 는 if 뿐만 아니라 for 나 while 같은 반복문 뒤에도 붙을 수 있음
- for 루프가 break 문에 의해 중단되지 않고 (Normal Termination), Iterable의 모든 요소를 순회했을 때
- else 블록이 실행
- for 루프가 break와 같은 비정상 종료일 때!
- else 블록이 실행 x
- for 루프가 break 문에 의해 중단되지 않고 (Normal Termination), Iterable의 모든 요소를 순회했을 때
- while문 활용
num = ""
sum = 0
while True:
num = int(input("숫자 입력: "))
if num == 0:
break
else:
sum += num
print(sum)
num = int(input("숫자 입력: "))
sum = 0
while num != 0:
sum += num
num = int(input("숫자 입력: "))
print(sum)
sum = 0
while (num := int(input("숫자 입력: "))) != 0:
sum += num
print(sum)
- 중첩 삼항 연산자
score = 75
result = "A" if score > 90 else "B" if score > 70 else "C"
print(result)
"""==========="""
if score > 90:
result = "A"
elif score > 70:
result = "B"
else:
result = "C"
- 연쇄 비교 (Chained comparison)
print(10 < 20 > 15 == 15) # (10 < 20) and (20 > 15) and (15 == 15)
- print(True and True and True) 이므로 True 출력
- 연산자 우선순위
print(not False or True and False)
- () 괄호
- == 비교 연산자
- not (1순위)
- not False → True
- and (2순위)
- True and False → False
- or (3순위)
- True or False → True
a = True
b = False
c = False
print(a or b and c == (a or b) and c)
- True or False and False == True and False
- True or False and False and False
- True or False
- True
- True or False
- True or False and False and False
- and 연산자 동작 방식
- 첫번째 falsy 값을 만나면 그 값을 즉시 반환
- 모두 truthy면 마지막 값을 반환
- True/False로 변환하는게 아니라 실제 값을 반환!
name = "Python"
print(name and "Is" and "Fun") # Fun 출력
- 단락 평가 (short-circuit evaluation)
- or 연산자는 첫번째가 truthy면 나머지를 평가하지 않음
data = []
flag = True
result = ""
# 리스트가 비어있는지 확인하고, 비어있다면 요소를 추가하는 것처럼 보이지만...
# 파이썬의 and/or 우선순위와 단락 평가를 주의깊게 보세요.
check = (flag or data.append("A")) and (len(data) > 0 or data.append("B"))
if data:
if "B" in data:
result = "Path 1"
else:
result = "Path 2"
else:
if not check:
result = "Path 3"
else:
result = "Path 4"
print(f"Data: {data}, Result: {result}")
- flag or data.append("A")
- flag == True이므로 단락평가가 발생하므로 data.append("A")는 실행되지 않음 → True
- len(data) > 0 or data.append("B")
- len(data) == 0이므로 False or data.append("B")로 data.append("B") 실행됨
- append()는 None을 반환 → None
- append() 함수는 자기 할 일만 하고 바로 종료하므로 None
- check = True and None
- and 연산자는 첫번째 falsy 값 즉시 반환 → check = None
- data = ["B"]
- 세 변수를 비교하기
- if (a==b) and (b==c):
- a==b==c 라고 하면 안되는 이유
- a==b 를 먼저 비교해서 True든 False든 결과가 나온 상태에서
- True/False == c 를 비교하는 경우엔
- 1/0 과 c를 비교하는 것이므로 잘못 실행될 수 있음
- a==b 를 먼저 비교해서 True든 False든 결과가 나온 상태에서
- a==b==c 라고 하면 안되는 이유
import sys
a,b,c = map(int,input("세 변의 길이: ").split())
print(a,b,c)
if (a <= 0 or b <= 0 or c <= 0) or (a+b <= c) or (a+c <= b) or (b+c <= a):
print("삼각형이 아닙니다.")
sys.exit(1)
else: # 삼각형은 삼각형일때
if (a**2 + b**2) == c**2 or (b**2 + c**2) == a**2 or (a**2 + c**2) == b**2:
tri = "직각삼각형"
elif (a==b) and (b==c):
tri = "정삼각형"
elif a==b or b==c or c==a:
tri = "이등변삼각형"
else:
tri = "일반 삼각형"
print(f"삼각형은 {tri}입니다.")
'Python 공부' 카테고리의 다른 글
| Truthiness (참 같은 값), Truthy/Falsy, 단락평가 (0) | 2026.01.09 |
|---|---|
| 가변 (Mutable) vs 불변 (Immutable) (0) | 2026.01.09 |
| isalpha, isdigit, isinstance 함수 (0) | 2026.01.09 |
| 프로그램 종료 함수 (0) | 2026.01.09 |
| 할당 vs 얕은 복사 vs 깊은 복사 / In-place 제자리 수정 vs Out-of-place 외부 생성 (0) | 2026.01.09 |