for문은 제어문에서 반복문이다. 범위를 주어주고 범위동안 반복하면서 데이터 처리를 할 때 사용한다.
기본형식
1 2
for () in (조건범위): (범위동안 반복하면서 처리하는 동작)
간단한 예를 보면
1 2 3
# 0 ~ 9 까지 반복을 하고 싶다면, for v2 in range(10): print('v2 is : ',v2)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
v2 is : 0 v2 is : 1 v2 is : 2 v2 is : 3 v2 is : 4 v2 is : 5 v2 is : 6 v2 is : 7 v2 is : 8 v2 is : 9 v3 is : 1 v3 is : 2 v3 is : 3 v3 is : 4 v3 is : 5 v3 is : 6 v3 is : 7 v3 is : 8 v3 is : 9
1 2 3 4 5 6 7 8
# 1부터 100까지의 합 print() print('1부터 100까지의 합 구하기 ( for문 이용 )') score = 0 for num in range(1, 101): score += num
print(score)
1
5050
# 시퀀스 (순서가 있는) 자료형 반복
문자열, 리스트, 튜플, 집합, 딕셔너리
리스트
1 2 3 4
names = ['Kim', 'Park', 'Cho', 'Yoo', 'Choi']
for v in names: print('You are : "', v)
1 2 3 4 5
You are : " Kim You are : " Park You are : " Cho You are : " Yoo You are : " Choi
문자열
1 2 3 4
word = "dreams"
for s in word: print('word : "', s)
1 2 3 4 5 6
word : " d word : " r word : " e word : " a word : " m word : " s
for num in numbers: if num == 33: print('found : 33 !') break else: print('not found : 33 !!')
1 2 3 4 5 6 7 8 9
not found : 33 !! not found : 33 !! not found : 33 !! not found : 33 !! not found : 33 !! not found : 33 !! not found : 33 !! not found : 33 !! found : 33 !
# for - else
for 문을 다 실행하고 마지막에 else가 실행이 된다. for 문 안에 break 구문이 작동이 되었다면, else 구문이 실행이 안된다. break문이 작동되지 않았다면 마지막에 else 구문이 작동된다.
for num in numbers2: if num == 33: print('found : 33 !') break else: print('not found : 33 !!') else: print('not found 33 ..............')
1 2 3 4 5 6 7 8 9 10 11 12 13 14
not found : 33 !! not found : 33 !! not found : 33 !! not found : 33 !! not found : 33 !! not found : 33 !! not found : 33 !! not found : 33 !! not found : 33 !! not found : 33 !! not found : 33 !! not found : 33 !! not found : 33 !! not found 33 ..............
# continue
for문 안에 사용된다. continue를 만나면 그 값은 넘어가고 다음 순서대로 간다. 조건문이 아닌 for문, 반복문으로 간다.
1 2 3 4 5 6 7 8
lt = ['1', 2, 5, True, 4.3, complex(4)]
for v in lt: if type(v) is float: continue print('타입 : ', type(v)) else: print('End')
1 2 3 4 5 6
타입 : <class 'str'> 타입 : <class 'int'> 타입 : <class 'int'> 타입 : <class 'bool'> 타입 : <class 'complex'> End