choco's story
파이썬 스터디 24 - while 반복문 본문
while 반복문
for문과의 비교
- for문 : 일정 횟수동안 반복
- while문 : '참(True)'이 나올 때 까지 반복
기본구조
while 불 표현식:
문장
무한반복 ex)
"."을 무한히 출력하는 예제 (에러남)
while True:
print(".", end="")

while 반복문 : for 반복문처럼 사용하기
ex)
i = 0
while i < 5:
print("{}번째 반복".format(i))
i += 1

while 반복문 : 상태 기반 반복
리스트 내부의 요소를 삭제하는 함수인 remove()는 중복되는 리스트의 요소 중, 맨 앞에 있는 요소만 삭제했었다.
→ while 반복문을 이용하여 모든 요소를 삭제해보자
ex1)
while 반복문 사용X인 remove(), while 반복문을 사용한 remove() 결과 비교
list = [1, 2, 1, 2, 2]
value = 2
list.remove(value)
print(list)

ex2)
list = [1, 2, 1, 2, 2]
value = 2
while value in list:
list.remove(value)
print(list)

while 반복문 : 시간 기반 반복
ex)
import time
number = 0
target_tick = time.time() + 5
while time.time() < target_tick:
number += 1
print("5초 동안 {}번 반복".format(number))

while 반복문 : break / continue
- break 키워드 : 반복문을 벗어날 때 사용
- continue 키워드 : 현재 반복을 생략하고 다음 반복으로 넘어갈 때 사용
break 키워드 ex)
i = 0
while True:
print("{}번째 반복".format(i))
i = i + 1
input_text = input("> 종료하시겠습니까?(y/n): ")
if input_text in ["y", "Y"]:
print("반복 종료")
break

continue 키워드 ex)
숫자가 10 이하인 경우에만 반복 → 10보다 큰 경우(이상) 반복하여 넘어가지 않고 print
numbers = [5, 15, 6, 20, 7, 25]
for number in numbers:
if number < 10:
continue
print(number)

'프로그래밍 언어 공부 (Coding Study) > 파이썬 (Python) 기본' 카테고리의 다른 글
| 파이썬 스터디 26 - reversed() 함수 (1) | 2024.09.20 |
|---|---|
| 파이썬 스터디 25 - min(), max(), sum() 함수 (1) | 2024.09.20 |
| 파이썬 스터디 23 - for 반복문 (0) | 2024.09.20 |
| 파이썬 스터디 22 - 딕셔너리 내부 확인 in / get() (0) | 2024.09.20 |
| 파이썬 스터디 21 - 딕셔너리의 값 추가 & 제거 (0) | 2024.09.20 |
