<형식>
while 조건 부분 :
수행 부분
<예시>
i = 1
while i<=4:
print("파이썬은 재밌다")
i += 1
2-1.
i = 2
while i<=100:
print(i)
i += 2
2-2.
i = 1
while i <= 50:
print(i * 2)
i += 1
i = 100
while i % 23 != 0:
i += 1
print(i)
<형식>
if 조건 부분 :
수행 부분 # 조건을 만족할 경우 수행 부분 실행
<예시>
temperature = 16
if temperature <= 10:
print("자켓을 입는다.")
else:
print("자켓을 입지 않는다.")
# Bad
if 점수가 90점 이상이다:
A를 준다
else:
if 점수가 80점 이상이다:
B를 준다
else:
if 점수가 70점 이상이다:
C를 준다
else:
F를 준다
# Good
if 점수가 90점 이상이다:
A를 준다
elif 점수가 80점 이상이다:
B를 준다
elif 점수가 70점 이상이다:
C를 준다
else:
F를 준다
def print_grade(midterm_score, final_score):
total = midterm_score + final_score # 중간, 기말 총합 점수
if total>=90:
print("A")
elif total>=80:
print("B")
elif total>=70:
print("C")
elif total>=60:
print("D")
else:
print("F")
<나의 답안>
i = 0
while i<=100:
i += 1
if i % 8 == 0 and i % 12 != 0:
print(i)
<모범답안>
i = 1
while i <= 100:
if i % 8 == 0 and i % 12 != 0:
print(i)
i += 1
💡 if 문 안에 i += 1를 쓰면 무한 루프에 빠질 수 있으므로 주의!
<내 답안> → 오답
i = 1
total = 0
while i<1000:
i += 1 # 얘가 여기있으면 이미 if문이 시작하기 전에 1을 더하고 시작하기 때문에 결과값이 달라진다.
if i % 2 ==0 or i % 3 == 0:
total += i
print(total)
<모범 답안>
i = 1
total = 0
while i<1000:
if i % 2 ==0 or i % 3 == 0:
total += i
i += 1
print(total)
<내 답안>
i = 1
count = 0
while i<=120:
if 120 % i == 0:
print(i)
count += 1
i += 1
print("120의 약수는 총 {}개 입니다.".format(count))
<모범 답안>
N = 120 # N은 상수로 지정해서 간단하게 표시해주기!
i = 1
count = 0
while i <= N:
if N % i == 0:
print(i)
count += 1
i += 1
print("{}의 약수는 총 {}개입니다.".format(N, count))
INTEREST_RATE = 0.12
APART_PRICE_2016 = 1100000000
year = 1988
bank_balance = 50000000
while year < 2016:
bank_balance = bank_balance * (1 + INTEREST_RATE)
year += 1
if bank_balance > APART_PRICE_2016 :
print("{:.0f}원 차이로 동일 아저씨 말씀이 맞습니다.".format(bank_balance - APART_PRICE_2016))
else:
print("{:.0f}원 차이로 미란 아주머니 말씀이 맞습니다.".format(APART_PRICE_2016 - bank_balance))
<모범 답안>
1-1. 임시 보관소를 사용하는 방법 → 어떤 언어에도 적용 가능한 장점
previous = 0
current = 1
i = 1
while i <= 50:
print(current)
temp = previous # previous를 임시 보관소 temp에 저장
previous = current
current = current + temp # temp에는 기존 previous 값이 저장돼 있음
i += 1
1-2. 파이썬에서 깔끔한 멋진 문법!
previous = 0
current = 1
i = 1
while i <= 50:
print(current)
previous, current = current, current + previous
i += 1
<모범 답안>
i = 1
while i <= 9:
j = 1
while j <= 9:
print("{} * {} = {}".format(i, j, i * j))
j += 1
i += 1
: while문의 조건 부분과 상관없이 반복문에서 나오고 싶으면 break문 사용
i = 100
while True:
# i가 23의 배수면 반복문을 끝냄
if i % 23 == 0:
break
i = i + 1
print(i)
115
: 현재 진행되고 있는 수행 부분을 중단하고 바로 조건 부분을 확인하고 싶은 경우
i = 0
while i < 15:
i = i + 1
# i가 홀수면 print(i) 안 하고 바로 조건 부분으로 돌아감
if i % 2 == 1:
continue
print(i)
2
4
6
8
10
12
14
아웅 오늘도 잘 보고갑니다..^^ 갈수록 레벨이 상승하심이...ㅎㅎㅎ
어렵네요잉! 수고하셧읍니다~~