[python] while문

while문 사용하기

while문의 사용 방식은 아래와 같다.

import random  # random 모듈을 가져옴

i = 0  # 초기식
while i < 10:  # while 조건식
    print('while', i)  # 반복할 코드
    i += 1  # 변화식

# random 모듈의 randint함수를 사용할 것이다.
# random.randint(a, b) 를 하면 [a, b]의 정수 난수가 생성
print('***random.randint(a, b)***')
i = 0
while i != 3:
    i = random.randint(1, 6)  # 난수 생성
    print(i)

# random.choice(시퀀스 객체)를 사용하면 시퀀스 객체에서 요소를 무작위로 가져온다.
print('***random.choice(seq)***')
dice = [1, 2, 3, 4, 5, 6]
i = 0
while i != 6:
    i = random.choice(dice)
    print(i)

무한루프 만들기

아래와 같은 방식으로 무한루프를 만들 수 있다.

# while True라고 판단하는 값:
#     실행할 코드
while True:
    print('T')

while 1:
    print('1')

while 'hello':
    print('str')

Updated:

Leave a comment