조건식을 검사하여 참인 경우까지 블록 내부 문장을 반복 수행
while_stmt ::= "while" expression ":" suite
["else"":" suite]
n = 100
s = 0
counter = 1
while counter <= n :
s = s + counter
counter +=1
print("Sum of 1 until %d : %d" % (n,s))
while 조건식 :
실행할 문장_1
실행할 문장_n
else :
실행할 문장_1
실행할 문장_n
집합데이터의 아이템이나 원소를 반복문을 통해 연산
for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite]
words = ['cat', 'window', 'sunflower']
>>> for w in words :
print(w, len(w))
cat 3
window 6
sunflower 9
>>> for w in words[:]:
if len(w) > 6 :
words.insert(0, w)
>>> words
['sunflower, 'cat', 'window', 'sunflower']
Range 함수는 출력 시 문자열 변환이 안됨
>>> print(range(10)) range(0, 10)
Range 함수는 iterator 기능을 이용하여 데이터를 생성하고 list타입으로 캐스팅하여 사용
>>> list(range(5)) [0, 1, 2, 3, 4]
range(시작, 끝-1, 스텝)
>>> for i in range(5): print(i) 0 1 2 3 4
break, continue, else -반복문에서 제어 변경을 위해서 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 : 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
문자 구조는 있으나 행위가 필요하지 않을 경우 유용하게 쓰임
무한 루프 발생시 keyboard interrupt (Ctrl + C)
>>> while True: pass >>> class MyEmptyClass: pass >>> def initlog(*args): pass
