Python - while(반복문)

닉네임유저·2023년 7월 31일

Python - 기초 문법

목록 보기
8/13
post-thumbnail

주어진 조건식이 Ture 인 동안 반복 작업을 수행하는 제어문

조건식이 처음부터 False 면 실행되지 않습니다.

while 조건식:
# 조건식이 True일 때 실행되는 코드 블록

선언 - while

while True:
 	조건식 ~ 제어문, 출력문

i 값이 10보다 크거나 같을때 1씩 증가한다.

i = 0
while i <= 10:
    print(i)
    i += 1

무한 루프 예제

# i 는 계속해서 1이 되고 0이된다.
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())

로또 번호 찍기

# set 은 중복이 되지 않는다.
import random

lotto = set()

while len(lotto) < 7:
    num = random.randint(1,45)
    lotto.add(num)

print(f'로또 번호 출력 : {lotto}')
profile
이것저것 다해보는 개발자

0개의 댓글