for 구문

다른 언어의 for문가 약간 다르다.이터레이터 방식으로 동작한다.

문자열이나 리스트처럼순서를 갖는 아이템들에 대해서도 동작한다.

기본구문

샘플 예제

>>>
 # Measure some strings:
... words = ['cat', 'window', 'defenestrate']

>>> for w in words:
...     print w, len(w)
...
cat 3
window 6
defenestrate 12

for 문은 여러 곳에서 사용 가능하다

문자열

>>> x = "Hello World"

>>> for c in x:
...     print c
... 
H
e
l
l
o

W
o
r
l
d

>>>

리스트

>>> x = ['sonic', 'yanggun', 'bonggu', 'dante']

>>> for name in x:
...     print name
... 
sonic
yanggun
bonggu
dante

>>>

사전

>>> x = {'name':'sonic', 'age':20, 'address':'seoul'}

>>> for key in x:
...     print key, x[key]
... 
age 20
name sonic
address seoul

>>>

파일

>>> f = open('test.txt', 'r')

>>> for line in f:
...     print line
... 
sonic
dante
bonggu
yanggun

while 구문

다른 언어의 while문과 동일하다.

주어진 식을 평가하여 그 결과가 더 이상 참이 아닌 거짓을 갖게 될 때까지 되풀이를 계속.

while 반복문은 x <= y와 같은 비교 표현을 가지며, 이 경우는 x가 y보다 커질 경우에 거짓으로 평가된다.

반복은 식이 거짓으로 평가될 때까지 처리를 계속하게 된다.

파이썬에서는 되풀이가 완료되었을 때 수행하도록 else 구문도 쓸 수 있다.

기본구문

샘플 예제

>>> x = 0

>>> y = 10

>>> while x <= y:
...     print 'The current value of x is: %d' % (x)
...     x += 1
... else:
...     print 'Processing Complete...'
...
The current value of x is: 0
The current value of x is: 1
The current value of x is: 2
The current value of x is: 3
The current value of x is: 4
The current value of x is: 5
The current value of x is: 6
The current value of x is: 7
The current value of x is: 8
The current value of x is: 9
The current value of x is: 10
Processing Complete...

else 문은 위와 같이반복 작업의 완료를 사용자에게 알려줄 수 있어 유용.

코드를 디버깅할 때나, 되풀이를 마치고 정리가 필요할 때에도 쓸모가 있다.

>>> total = 0

>>> x = 0

>>> y = 20

>>> while x <= y:
...     total += x
...     x += 1
... else:
...     print total
...     total = 0
...
210

range 구문

숫자 범위에 대하여 반복을 하거나 특정한 범위의 숫자를 나열하도록 해주는 특별한 함수

수학적인 반복에 특히 유용하지만, 간단한 반복을 위해서도 사용

range 형식

순서적인 숫자를 반복해야 할 경우 내장함수인 range를 사용하면 편하다.

사용 예제 코드 1

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

사용 예제 코드 2

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> range(5, 10)
[5, 6, 7, 8, 9]

>>> range(0, 10, 3)
[0, 3, 6, 9]

>>> range(-10, -100, -30)
[-10, -40, -70]

사용 예제 코드 3

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']

>>> for i in range(len(a)):
...     print i, a[i]
...
0 Mary
1 had
2 a
3 little
4 lamb

range에서 리스트 생성

>>> my_number_list = list(range(10))

>>> my_number_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range 주의점

range() 함수는 모든 값이 채워진 형태로 리스트를 생성,매우 큰 범위를 지정하면 메모리 모두 소진

대안 함수 : xrange()

xrange()로 생성되는 객체는 검색이 요청되는 시점에 값을 계산,매우 큰 범위를 표현할 때는 사용하는 것이 좋다.

반복 구문에서 break, continue, else

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'equals', x, '*', n/x)
...             break
...     else:
...         # loop fell through without finding a factor
...         print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

continue 구문

>>> for num in range(2, 10):
...     if num % 2 == 0:
...         print("Found an even number", num)
...         continue
...     print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

break 문

continue 문과 비슷하게, break 문을 반복문 내에서 사용할 수 있다.

break 문은 되풀이를 완전히 끝내고 프로그램이 그 다음 작업으로 넘어가도록 할 때 사용한다.

현재의 반복만 끝내고 다음 반복으로 진행하는 continue와는 다르다.

>>> x = 10

>>> while True:
...     if x == 0:
...         print('x is now equal to zero!')
...         break
...     if x % 2 == 0:
...         print x
...     x -= 1
...
10
8
6
4
2
x is now equal to zero!

색인을 자동으로 표현해주는 Enumerate() 함수

>>> myList = ['jython','java','python','jruby','groovy']

>>> for index, value in enumerate(myList):
...     print(index, value)
...
0 jython
1 java
2 python
3 jruby
4 groovy

pass 구문

아무것도 안하는 구문

# 반복문에서의 pass
while True:
    pass  


# 가장 작은 클래스
class MyEmptyClass:
    pass

# 함수에서
def initlog(name):
    pass

사전형태의 데이타를 반복

>>> my_dict = {'Jython':'Java', 'CPython':'C', 'IronPython':'.NET','PyPy':'Python'}

>>> for key in my_dict:
...     print key
...
Jython
IronPython
CPython
PyPy

results matching ""

    No results matching ""