# while 반복문
while 조건 부분: # 불린
수행 부분 # 반복 시키고 싶은 며령
ex.1)
i = 1
while i <= 3:
print("하는 잘 생겼다!")
i += 1
ex.2) 1이상 100이하의 짝수 모두 출력
i = 1
while i <= 50:
print(i * 2)
i += 1
ex.3) 100 이상의 자연수 중 가장 작은 23의 배수 출력
i = 100
while i % 23 != 0 :
i += 1
print(i)
# if else
if 조건 부분:
수행부분
while 다운로드 안 받은 이미지가 있다:
다음 이미지를 본다
if 이미지가 png 파일이다:
이미지를 다운로드 받는다
else:
print("png가 아닙니다!")
ex.1)
temperature = 8
if temperature <= 10:
print("자켓을 입는다.")
else:
print("자켓을 입지 않는다.")
ex.2)
if 온도가 10도 이하다:
자켓을 입는다
else:
if 온도가 15도 이하다:
긴팔을 입는다
else:
반팔을 입는다
-> elfe
if 점수가 90점 이상이다:
A를 준다
elif 점수가 80점 이상이다:
B를 준다
elif 점수가 70점 이상이다:
C를 준다
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")
ex.3) 100이하 자연수 중 8의 배수이지만 12의 배수는 아닌 것 모두 출력
i = 1
while i <= 100:
if i % 8 == 0 and i % 12 != 0:
print(i)
i += 1
ex.4) 1000보다 작은 자연수 중 2 또는 3의 배수의 합
i = 1
total = 0
while i < 1000:
if i % 2 == 0 or i % 3 == 0:
total += i
i += 1
print(total)
ex.5) 정수 120의 약수 모두 출력, 총 명개의 약수가 있는지 출력
N = 120
i = 1
count = 0
while i <= N:
if N % i == 0:
print(i)
count += 1
i += 1
print("{}의 약수는 총 {}개 입니다.".format(N, count))
ex.6)
INTEREST_RATE = 0.12
APARTMENT_PRICE_2016 = 1100000000
year = 1988
bank_balance = 50000000
while year < 2016:
bank_balance = bank_balance * (1 + INTEREST_RATE)
year += 1
if bank_balance > APARTMENT_PRICE_2016:
print("{}원 차이로 동일 아저씨 말씀이 맞습니다.".format(int(bank_balance - APARTMENT_PRICE_2016)))
else:
print("{}원 차이로 미란 아주머니 말씀이 맞습니다.".format(int(APARTMENT_PRICE_2016 - bank_balance)))
ex.7) 피보나치부열(Fibonacci Swquence)
1,1,2,3,5,8,13,21,31,34,55, ...
previous = 0
current = 1
i = 1
while i <= 50:
print(current)
temp = previous
previous = current
current = current + temp
i += 1
< 간단히 >
previous = 0
current = 1
i = 1
while i <= 50:
print(current)
previous, current = current, current + previous
i += 1
# break 문
만약 while문의 조건 부분과 상관 없이 반복문에서 나오고 싶으면, break 문을 사용
i = 100
while true:
# i 가 23의 배수면 반복문 끝냄
if i % 23 == 0:
break
i = i + 1
print(i)
# continue문
현재 진행되고 있는 수행부분을 중단하고 바로 조건 부분을 확인하고 싶으면 continue문을 사용
i = 0
while i < 15:
i = i + 1
# i가 홀수면 print(i) 안하고 바로 조건 부분으로 돌아감
if i % 2 == 1:
continue
print(i)
'파이썬 Study' 카테고리의 다른 글
| [Python] 파이썬 모듈 (0) | 2022.02.03 |
|---|---|
| 4. 토픽 (0) | 2022.01.21 |
| 2. 추상화 (0) | 2022.01.16 |
| 1. 자료형 (0) | 2022.01.05 |