컴퓨터는 사람보다 비슷한 작업을 반복하는 일을 더 잘한다. 반복이 매우 흔한 일이어서, 파이썬에서 반복 작업을 쉽게 하도록 몇 가지 반복문 기능을 제공한다.
n = 5
while n > 0: # n이 0보다 크면 반복
print(n)
n = n - 1
print('Blastoff!')
print(n)
# 결과
5
4
3
2
1
Blassoff!
0
n이 0보다 크면 while문은 계속 실행한다. n=5이기 때문에 while문의 조건에 만족하므로 반복문을 실행한다. n=0이 되면 while문 조건에 만족하지 않으므로 반복문을 빠져나오게 된다.
while 다음
: (콜론)
을 써주는 것을 잊지말자!
while True:
line = input('> ')
if line == 'done': # 만약 line이 'done'이면
break # 반복문 빠져나오기
print(line)
print('Done!')
# 결과
# > hello there로 입력
# hello there로 출력됨
# > finished로 입력
# finished로 출력됨
# > done로 입력
# Done!으로 출력됨
break
문을 사용하면 된다.continue
문을 사용한다.while True:
line = input('> ')
if line[0] == '#' : # 입력단어 첫 번째가 #이라면
continue # 다음 코드를 실행 하지않고 loop 시작점으로 감
if line == 'done' :
break
print(line)
print('Done!')
# 결과
# > hello there 입력
# hello there로 출력
# # don't print this
# > print this! 입력
# print this!로 출력
# > done 입력
# Done!
while문은 조건문이 거짓이 되기 전까지 계속 실행 되기 때문에 "불확정 루프" 라고 부른다.
코드의 길이가 길어지고 종료 조건이 복잡해지면 코드가 정말 종료할 수 있는지 불분명 해진다. while문을 이용해 많은 것을 할 수 있지만 대부분의 반복문을 만들기 위해 확정 루프라고 불리는 것을 사용한다.
for i in [5, 4, 3, 2, 1] :
print(i)
print('Blastoff!')
# 결과
5
4
3
2
1
Blastoff!
포함 연산자인 in
을 사용하여 반복변수 i가 리스트 [5,4,3,2,1]을 순서대로 인덱싱한다. 즉, 5 4 3 2 1 이 출력이 된다.
friends = ['Connect', 'Korea', 'NHN']
for friend in friends:
print('Happy New Year!! ', friend)
print('Done!')
# 결과
Happy New Year!! Connect
Happy New Year!! Korea
Happy New Year!! NHN
Done!
문자열에서도 마찬가지로 in
을 사용하여 friend라는 반복변수를 friends 리스트안을 순서대로 인덱싱한다.
largest_so_far = -1 # 작은 수로 -1로 선언
print('Before', largest_so_far) # 최초의 값과 루프 이후의 값을 비교하기 위해 print 함수로 현재의 값을 확인
numbers = [9, 41, 12, 3, 74, 15] # numbers라는 int를 원소로 가지는 list를 선언
for the_num in numbers
if the_num > largest_so_far : # 현재의 값(the_num)이 현재 가장 큰 값이 할당 되어 있는 largest_so_far보다 크다면
largest_so_far = the_num # largest_so_far의 값을 the_num으로 바꿔줌
print('largest_so_far: ', largest_so_far, 'current number: ',the_num)
print('After', largest_so_far)
Before -1
largest_so_far: 9 current number: 9
largest_so_far: 41 current number: 41
largest_so_far: 41 current number: 12
largest_so_far: 41 current number: 3
largest_so_far: 74 current number: 74
largest_so_far: 74 current number: 15
After 74
zork = 0
print('Before', zork)
numbers = [9, 41, 12, 3, 74, 15]
for thing in numbers :
zork = zork + 1
print(zork, thing)
print('After', zork)
# 결과
Before 0
1 9
2 41
3 12
4 3
5 74
6 15After 6
zork = 0
print('Before', zork)
numbers = [9, 41, 12, 3, 74, 15]
for thing in numbers :
zork = zork + thing
print(zork, thing)
print('After', zork)
# 결과
Before 0
9 9
50 41
62 12
65 3
139 74
154 15
After 154
count = 0 # 평균을 전체 원소의 수로 나누기 위해 total number를 확인합니다.
sum = 0
print('Before', count, sum)
numbers = [9, 41, 12, 3, 74, 15]
for value in numbers :
count = count + 1
sum = sum + value
print(count, sum, value)
print('After', count, sum, sum/count)
# 결과
Before 0 0
1 9 9
2 50 41
3 62 12
4 65 3
5 139 74
6 154 15
After 6 154 25.666666666666668
print('Before')
numbers = [9, 41, 12, 3, 74, 15]
for value in numbers :
if value > 20:
print('Large number', value)
print('After')
# 결과
Before
Large number 41
Large number 74
After
found = False
print('Before', found)
numbers = [9, 41, 12, 3, 74, 15]
for value in numbers :
if value == 3 :
found = True
print(found, value)
break
print('After', found)
# 결과
Before False
True 3
After True
is
와 is not
의 연산자는 자료형과 값이 동일할 때 True를 반환한다. 예를 들어, 0 == 0.0은 True이지만 0 is 0.0은 False입니다. 값은 동일하지만 자료형이 전자는 int이고 후자는 float 이기 때문이다.smallest = None
print('Before')
numbers = [9, 41, 12, 3, 74, 15]
for value in numbers :
if smallest is None :
smallest = value
elif value < smallest :
smallest = value
print(smallest, value)
print('After', smallest)
# 결과
Before
9 9
9 41
9 12
3 3
3 74
3 15
After 3