while 조건문:
# 조건문이 참(True)인 경우 실행할 코드
# ...
treeHit = 0 # 나무를 찍은 횟수
while treeHit < 10:
treeHit += 1 # 나무를 한 번 찍는다.
print(f"나무를 {treeHit}번 찍었습니다.") # 진행 상태 출력
if treeHit == 10:
print("나무 넘어갑니다.") # 목표 달성 시 출력
coffee = 10 # 남은 커피의 수
while True: # 무한 루프 시작
money = int(input("돈을 넣어 주세요: ")) # 사용자로부터 돈을 입력받음
if money == 300:
print("커피를 줍니다.") # 정확한 금액일 때 커피 제공
coffee -= 1 # 커피 수 감소
elif money > 300:
print(f"거스름돈 {money - 300}를 주고 커피를 줍니다.") # 거스름돈과 함께 커피 제공
coffee -= 1 # 커피 수 감소
else:
print("돈을 다시 돌려주고 커피를 주지 않습니다.") # 부족한 금액일 때 메시지 출력
if coffee == 0:
print("커피가 다 떨어졌습니다. 판매를 중지합니다.") # 커피 소진 시 판매 중지
break # 무한 루프 종료
a = 0 # 반복 변수 초기화
while a < 10:
a += 1
if a % 2 == 0: # a가 짝수이면
continue # 다음 반복으로 넘어간다
while 문 기본 구조
python
Copy code
while 조건문:
# 조건문이 참인 경우에 실행할 코드 블록
수행할_문장1
수행할_문장2
...
treeHit = 0
while treeHit < 10:
treeHit += 1
print(f"나무를 {treeHit}번 찍었습니다.")
if treeHit == 10:
print("나무 넘어갑니다.")
a = 0
while a < 10:
a += 1
if a % 2 == 0:
continue
print(a)
while True:
print("Ctrl+C를 눌러야 while문을 빠져나갈 수 있습니다.")
while True는 조건문이 항상 참이기 때문에 무한 루프가 된다.
사용자가 Ctrl+C를 누르기 전까지 무한히 반복한다.
for 변수 in 리스트(또는 튜플, 문자열):
수행할_문장1
수행할_문장2
...
test_list = ['one', 'two', 'three']
for i in test_list:
print(i)
a = [(1,2), (3,4), (5,6)]
for (first, last) in a:
print(first + last)
marks = [90, 25, 67, 45, 80]
for number, mark in enumerate(marks, start=1):
if mark >= 60:
print(f"{number}번 학생은 합격입니다.")
else:
print(f"{number}번 학생은 불합격입니다.")
marks = [90, 25, 67, 45, 80]
for number, mark in enumerate(marks, start=1):
if mark < 60:
continue
print(f"{number}번 학생 축하합니다. 합격입니다.")
add = 0
for i in range(1, 11):
add += i
print(add)
1부터 10까지의 합계를 add에 저장한 후 출력한다.
for i in range(2, 10):
for j in range(1, 10):
print(i * j, end=" ")
print('')
예)
첫번째 수: 24
두번째 수: 16
24와 16의 최대 공약수: 8
# 두 수를 입력 받아서 최대 공약수를 출력하는 프로그램을 작성해 보세요.
# 예)
# 첫번째 수: 24
# 두번째 수: 16
# 24와 16의 최대 공약수: 8
a = int(input('첫번째 수: '))
b = int(input('두번째 수: '))
if a > b:
a, b = b, a # 첫번째 수를 작은 수로, 두번째 수를 큰 수로 설정
for i in range(a, 0, -1):
if a % i == 0 and b % i == 0: # 공약수
print(f'{a}와 {b}의 최대 공약수: {i}')
break # 최대 공약수를 구했으므로 더 이상 반복하지 않음
예)
[20, 70, 87, 99, 82, 60]['정상', '정상', '비만', '비만', '비만', '정상']
weights = [20, 70, 87, 99, 82, 60]
results = []
for w in weights:
if w >= 80:
results.append('비만')
else:
results.append('정상')
print(weights)
print(results)
weights = [20, 70, 87, 99, 82, 60]
def checkWeights(w):
if w >= 80: return '비만'
else: return '정상'
results = list(map(checkWeights, weights))
print(weights)
print(results)
예)
20 : 정상
80 : 비만
weights = [20, 70, 87, 99, 82, 60]
results = ["정상" if weight < 80 else "비만" for weight in weights]
for i in range(len(weights)):
print(f"{weights[i]} : {results[i]}")
weights = [20, 70, 87, 99, 82, 60]
results = ["정상" if weight < 80 else "비만" for weight in weights]
for index, weight in enumerate(weights):
print(f"{weight} : {results[index]}")
weights = [20, 70, 87, 99, 82, 60]
results = ["정상" if weight < 80 else "비만" for weight in weights]
for weight, result in zip(weights, results):
print(f"{weight} : {result}")
아래 요구사항을 만족하는 프로그램을 작성해 보세요.
프로그램에서 생성한 0 보다 크고, 100 보다 작은 임의의 난수를 맞추는 게임
사용자가 숫자를 입력하면 메시지를 출력
생성한 숫자 보다 크면 "크다"
생성한 숫자 보다 작으면 "작다"
생성한 숫자와 입력한 숫자가 일치하면 "00번만에 맞췄습니다."
사용자가 숫자를 입력하는 기회는 10번으로 제한
남은 기회를 출력
모든 기회가 사용되면 프로그램을 종료
import random
target = random.randint(1, 99)
count = 0
print("숫자 맞추기 게임을 시작합니다.")
while True:
count += 1
num = int(input("1 ~ 99 사이의 숫자를 입력하시오."))
if num == target:
print(f"정답입니다. {count}번 만에 맞추셨습니다.")
break
elif num > target:
print("입력한 숫자가 정답 보다 큽니다.")
else:
print("입력한 숫자가 정답 보다 작습니다.")
if count == 10:
print(f"모든 기회를 소진하였습니다. 정답은 {target} 입니다.")
break
else:
print(f'{10-count} 기회가 남았습니다.')
요구사항
사용자로부터 영어 문장을 입력 받음
입력받은 문장을 구성하고 있는 임의의 단어를 하나 추출해서, 해당 단어를 맞추는 게임
단어의 길이 만큼 "_"를 출력 ⇒ 단어: _
사용자가 알파벳을 입력하면 해당 위치에 알파벳을 출력 ⇒ t를 입력 _t__t
단어를 맞추는 회수는 10번으로 제한
주어진 회수 안에 단어를 맞추면 단어와 시도 회수를 출력
import re
import random
#words = input('여러 단어로 구성된 문장을 입력하세요. ')
words = "Visit BBC for trusted reporting on the latest world and US news, sports, business, climate, innovation, culture and much more."
print(f"입력 : {words}")
# 문장부호를 제거 ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ ] ^ _ ` { | } ~ \
words = re.sub(r'[!"#$%&\'()*+,-./:;<=>?@\[\]^_\`{|}~\\\\]', '', words)
# 공백문자를 기준으로 단어를 분리
words = words.split()
# 임의의 단어를 추출
rand_word = list(words[random.randrange(len(words))])
# 화면에 출력할 내용
disp_word = list('_' * len(rand_word))
print(f'힌트 >>> {''.join(disp_word)}')
try_count = 0
while True:
try_count += 1
alpha = input(f'{try_count} 시도 >>> 영어 단어를 구성하는 알파벳을 입력하세요. ')
for i, a in enumerate(rand_word):
if alpha == a:
disp_word[i] = alpha
print(f'힌트 >>> {''.join(disp_word)}')
if disp_word.count('_') == 0:
print(f'정답 "{''.join(rand_word)}"를 {try_count}번 만에 맞췄습니다.')
break
elif try_count >= 10:
print(f'10번에 기회가 모두 끝났습니다. 정답은 "{''.join(rand_word)}" 입니다.')
break