while 문
while 문은 조건이 참일 때까지 반복 실행
a = 1
while a <= 5:
print(a, end=',')
a += 1
print('\na:', a)
# 출력:
# 1,2,3,4,5,
# a: 6
while 문과 else 문
else 구문은 while 반복이 거짓이 될 때 실행
a = 8
while a <= 5:
print(a, end=',')
a += 1
else:
print('while문 수행')
print('\na:', a)
# 출력:
# while문 수행
# a: 8
이중 while 문
두 개의 중첩된 반복문을 사용하여 복잡한 반복 작업 처리
i = 1
while i <= 3:
j = 1
while j <= 4:
print('i=' + str(i) + '\j=' + str(j))
j = j + 1
i = i + 1
print('while구문 종료됨')
# 출력:
# i=1\j=1
# i=1\j=2
# i=1\j=3
# i=1\j=4
# i=2\j=1
# i=2\j=2
# i=2\j=3
# i=2\j=4
# i=3\j=1
# i=3\j=2
# i=3\j=3
# i=3\j=4
# while구문 종료됨
print('1~100 사이에서 3의 배수의 합 출력')
i = 1
hap = 0
while i <= 100:
if i % 3 == 0:
hap += i
i += 1
print('합은' + str(hap))
# 출력: 합은1683
colors = ['red', 'green', 'blue', 'white', 'black']
a = 0
while a < len(colors):
print(colors[a], end=' ')
a += 1
# 출력: red green blue white black
while 문에서 continue와 break
continue는 특정 조건에서 다음 반복으로 넘어가고, break는 반복문을 완전히 종료
a = 0
while a < 10:
a += 1
if a == 5:
continue # 5를 건너뜀
if a == 7:
break # 7에서 반복문 탈출
print(a, end=' ')
# 출력: 1 2 3 4 6
사용자가 0을 입력할 때까지 숫자를 계속 입력받아 짝수인지 판별
while True:
a = int(input("확인할 숫자를 입력하세요?"))
if a == 0:
print('프로그램 종료')
break
elif a % 2 == 0:
print('%d는 짝수' % (a))
# 출력 예시:
# 확인할 숫자를 입력하세요? 34
# 34는 짝수
# 확인할 숫자를 입력하세요? 0
# 프로그램 종료
print('=='*20)
print('여기는 커피 전문점')
print('가격은 3000원, 오늘 남은 양은 3잔')
print('=='*20)
coffee = 3
while True:
money = int(input("지불할 금액 입력?"))
if money == 3000:
print('커피 한잔 받으세요')
coffee -= 1
elif money > 3000:
print('커피 받으시고 잔돈 %d원 받으세요' % (money - 3000))
coffee -= 1
else:
print('금액이 부족합니다.')
print('남은 커피는 %d잔입니다.' % coffee)
if not coffee: # coffee가 0일 경우
print('오늘 장사 끝')
break
# 출력 예시:
# ========================================
# 여기는 커피 전문점
# 가격은 3000원, 오늘 남은 양은 3잔
# ========================================
# 지불할 금액 입력? 5000
# 커피 받으시고 잔돈 2000원 받으세요
# 지불할 금액 입력? 2000
# 금액이 부족합니다.
# 남은 커피는 2잔입니다.
# 지불할 금액 입력? 3000
# 커피 한잔 받으세요
# 지불할 금액 입력? 3000
# 커피 한잔 받으세요
# 오늘 장사 끝
import random # 모듈 import
num = random.randint(1, 10) # 1부터 10 사이의 난수 생성
print(num)
# 출력 예시:
# 5
사용자가 컴퓨터가 생각한 1~10 사이의 숫자를 맞추는 게임
while True:
su = int(input("1~10 사이의 컴퓨터 생각 숫자?"))
if su == num:
print('성공~' * 5)
break
elif su < num:
print('더 큰 수를 입력하세요')
else:
print('더 작은 수를 입력하세요')
# 출력 예시:
# 1~10 사이의 컴퓨터 생각 숫자? 7
# 더 작은 수를 입력하세요
# 1~10 사이의 컴퓨터 생각 숫자? 5
# 성공~성공~성공~성공~성공~