반복문

while구문은 다른 프로그래밍 언어와 별반 다를 것이 없다.
    
    a, b = 0, 1
    while b< 50:
        print(b, end=' ')
        a, b = b, a+b        

위 코드는 피보나치 수열을 출력한다.


특이하게도, while-else 구문도 존재하는데, while 뒤의 조건이 False가 되면 else 문으로 분기한다.
    
    a = 0
    while a< 10:
        print (a)
        a += 1
    else:
        print("끝" )
 

do-while 문은 없고, while 뒤의 조건문이 True이면 무한루프가 된다.
    
    a = 0
    while True:
        print (a)
        a += 1
        if a>=10 : break





또 다른 하나의 반복 구문은 for-in인데, 이것은 다른 프로그래밍 언어의 for-each 혹은 for : 구문 등과 유사하다.
    
    for item in [1 , 2, 3, 4, 5]:
        print(item)
  
for 다음에는 변수를, in 다음에는 리스트, 튜플, 딕셔너리 등의 컨테이너를 기술한다. 물론, 문자열도 쓸 수 있다.
    
    for char in "가나다라마바사" :
        print(char)



그런데, 파이썬에는 for만을 사용하는 전통적인 for(;;)구문은 없다.
만일, 증감하는 정수값이 필요한 경우에는 in 뒤에 range() 함수를 사용할 수 있는데,
        
    for i in range(5 ) :
        print(i, end=' ') # 0 1 2 3 4

    for i in range(1 , 5) :
        print(i, end=' ') # 1 2 3 4 


또한, enumerate() 함수를 사용할 수도 있다.
    
    for i, char in enumerate("가나다라마바사") :
        if char=="다":
            print("{}번째 글자!" .format(i)) # 2번째 글자!

enumerate() 함수의 시작값은 0부터인데, 함수의 두번째 매개변수를 통해서 이 값을 변경할 수도 있다.




break와 continue 같은 분기문은 다른 프로그래밍 언어와 마찬가지의 규칙을 따른다.


댓글

  1. In an more and more crowded market, we did a deep dive and analyzed the entire sports activities betting apps out there in Illinois 온라인카지노 to come up with what we think is the best. There isn't any shortage of choices, together with products from Ceasars, DraftKings, FanDuel, Barstool, BetMGM, PointsBet and BetRivers. At this very moment, Bleacher Nation is offering seven wonderful Illinois online sports activities betting promos.

    답글삭제

댓글 쓰기

이 블로그의 인기 게시물

Project Euler - 3

메인 스크립트

예외 처리