주어진 조건식이 Ture 인 동안 반복 작업을 수행하는 제어문
조건식이 처음부터 False 면 실행되지 않습니다.
while 조건식:
# 조건식이 True일 때 실행되는 코드 블록
선언 - while
while True:
조건식 ~ 제어문, 출력문
i 값이 10보다 크거나 같을때 1씩 증가한다.
i = 0
while i <= 10:
print(i)
i += 1
무한 루프 예제
while i <= 10:
i=0
print(i)
i += 1
사용자로부터 입력받은 숫자까지 합을 구하기
total = 0
num = int(input('숫자를 입력하시오 : (0 이상의 정수) : '))
i = 1
while i <= num:
total += i
i += 1
print(f'{num} 의 합은 ', total)
break ( 반복 탈출 )
사용자가 특정 문자를 입력할 때 까지 계속해서 입력 받기
while True:
user_input = input("종료하려면 'exit'를 입력하세요: ")
if user_input.lower() == 'exit':
break
continue - 반복 중단 , 처음으로 다시 돌아가기
i = 1
while i <= 10:
if i % 2 == 0:
i += 1
continue
print(i)
i += 1
else - 반복 종료 후, 추가 실행 구문
i = 1
while i <= 5:
if i == 5:
print("반복 종료")
break
print(i)
i += 1
else:
print("정상 종료")
.pop() 으로 역순 출력
a = ['soda', 'coke', 'cider']
while True:
if not a:
break
print(a.pop())
로또 번호 찍기
import random
lotto = set()
while len(lotto) < 7:
num = random.randint(1,45)
lotto.add(num)
print(f'로또 번호 출력 : {lotto}')