[Python] 반복문

1 minute read

[Python] 반복문

Inflearn Study

링크: https://www.inflearn.com/

  • 인프런에서 “파이썬 무료 강의 (기본편) - 6시간 뒤면 나도 개발자” 강의를 들으며 혼자 공부한 내용입니다.

for문

for waiting_no in range(1, 6): # 1 2 3 4 5
    print("대기번호: {0}".format(waiting_no))
starbucks = ["아이언맨", "토르", "그루트"]
for customer in starbucks:
    print("{0}, 커피가 준비되었습니다.".format(customer))
  • for문의 기본 구조

    • for [변수] in [문자열/리스트/튜플]:

      ​ [실행 부분]


한 줄 for문

students = [1, 2, 3, 4, 5]
students = [i+100 for i in students]
print(students) # 101, 102, 103, 104, 105

# 학생 이름을 길이로 변환
students = ["Iron man", "Thor", "Groot"]
students = [len(i) for i in students]
print(students)

# 학생 이름을 대문자로 변환
students = ["Iron man", "Thor", "Groot"]
students = [i.upper() for i in students]
print(students)

while 문

customer = "토르"
index = 5
while index >= 1:
    print("{0}, 커피가 준비 되었습니다. {1}번 남았어요".format(customer, index))
	index -= 1 
    if (index == 0):
        print("커피는 폐기처분 되었습니다.")
  • while문 기본 구조

    • while [조건문]:

      ​ [실행 부분]

  • 조건문이 참(True)인 경우 내부 실행 부분을 수행

  • 조건문이 거짓(False)인 경우 while문을 빠져나갑니다.

customer = "아이언맨"
index = 1
while True:
    print("{0}, 커피가 준비 되었습니다. {1}번 남았어요".format(customer, index))
    index += 1
  • while True: 조건문이 True 이므로 무한 반복합니다.
    • 종료시키려면 break문을 작성하거나
    • Ctrl+C를 누르면 종료 됩니다.

break와 continue

  • for문

    absent = [2, 5] # 결석
    no_book = [7] # 책을 깜빡했음
    for student in range(1, 11):
        if student in absent:
            continue 
            # absent 리스트에 학생이 있으면 아래 수행 부분은 무시하고 for문으로 올라감
        elif student in no_book:
            print("오늘 수업 여기까지. {0}는 교무실로 따라와.".format(student))
            break # no_book 리스트에 학생이 있으면 반복문 종료
        print("{0}, 책을 읽어봐.".format(student))
    
    • continue: 조건이 참이면 반복문 계속 진행
    • break: 조건이 참이면 반복문 종료
  • while 문

    absent = [2, 5] # 결석
    no_book = [7] # 책을 깜빡했음
    index = 0
    while index < 10:
        index += 1
        if index in absent:
            continue 
            # absent 리스트에 학생이 있으면 아래 수행 부분은 무시하고 while문으로 올라감
        elif index in no_book:
            print("오늘 수업 여기까지. {0}는 교무실로 따라와.".format(index))
            break # no_book 리스트에 학생이 있으면 반복문 종료
        print("{0}, 책을 읽어봐.".format(index))
    

Leave a comment