Python Basics - For Loops, Break, Continue

Jayson Hwang·2022년 4월 30일
0

10. for(반복문)

일련의 동작을 반복하도록 해야할 때 사용

for (변수명) in (iterator)
  • iterator에는 리스트, 튜플, 딕셔너리, 집합등 iterable(가지고 있는 값을 한번에 하나씩 반환할 수 있는 개체)한 값이 와야함
  • A for loop is used for iterating over a sequence(that is either a list, a tuple, a dictionary, a set, or a string).

10-1. for 예제

for waiting_no in [1, 2, 3, 4]:
	print("waiting no. : {0}".format(waiting_no))

#waiting no. : 1
#waiting no. : 2
#waiting no. : 3
#waiting no. : 4


<<'range'의 경우 (시작조건, 종료조건, 스텝(생략가능))>>
<<for in range(start_value, end_value, step)>>

for waiting_no in range(1, 6):
    print("waiting no. : {0}".format(waiting_no))

#waiting no. : 1
#waiting no. : 2
#waiting no. : 3
#waiting no. : 4
#waiting no. : 5

<<Step(스텝)이 있는 경우>>

our_list = []
for i in range(0, 10, 2):
	our_list.append(i)
print(our_list)

# [0, 2, 4, 6, 8]


<<Step(스텝)이 이 음수인 경우, 반복문의 거꾸로 수행>>
our_list = []
for i in range(10, 0, -2):
	our_list.append(i)
print(our_list)

# [10, 8, 6, 4, 2]
starbucks = ["Kevin", "Jay", "Carl", "Chris"]
for customer in starbucks:
	print("{0}, your coffee is here.".format(customer))

#Kevin, your coffee is here.
#Jay, your coffee is here.
#Carl, your coffee is here.
#Chris, your coffee is here.

10-2. 한줄로 끝내는 for문 활용법

#출석 번호가 1 2 3 4 5 앞에 100을 붙이기로함 -> 101, 102, 103, 104, 105
students = [1,2,3,4,5]
print(students)
students = [i+100 for i in students]
print(students)

-------------------------
[1, 2, 3, 4, 5]
[101, 102, 103, 104, 105]
-------------------------
# 학생 이름을 길이로 변환
students = ["Iron man", "Thor", "I am groot"]
students = [len(i) for i in students]
print(students)

-----------
[8, 4, 10]
-----------
# 학생 이름을 대문자로 변환
students = ["Iron man", "Thor", "I am groot"]
students = [i.upper() for i in students]
print(students)

----------------------------------
['IRON MAN', 'THOR', 'I AM GROOT']
----------------------------------


11. Continue & Break

  • Continue:: 반복문 맨 처음으로 돌아가기 (남아있는 실행문을 무시한 채)

  • Break:: 반복문 빠져나가기


11-1. Continue

반복문을 계속 돌다가 특정 조건을 만족할 때 아래 코드들을 무시하고 바로 반복문의 맨 위로 올라가게 만들어주는 것.(즉, 중간에서 맨 처음으로 올라가는 것)

a = 0 # a가 0부터 시작
while a < 10 : # a가 10미만일 때까지 출력
    a = a + 1 # 출력 후 a + 1
    if a % 2 == 0 : # a를 2로 나눴을 때 나머지가 0이라면
        continue # 다시 맨 처음 문장으로
    print(a) # 만약 홀수라면 a 출력
    
# 1
# 3
# 5
# 7
# 9

11-2. Break

반복문을 수행하다가 특정 조건이 만족된 경우에 빠져나오고 싶을 때 사용

book = 10 # 책 10권
people = 20 # 사람 20명, 선착순 10명에게만 책 증정 
while people : # 1번째 사람부터 차례대로
    print("축하합니다!")
    book = book - 1 # 책을 받을 때마다 남은 권수는 하나씩 줄어든다
    print("남은 책은 %d권 입니다." %book)
    if book == 0 : # 만약 책이 모두 소진되면
        print("끝났습니다. 다음기회에!")
        break # 프로그램이 종료된다.
        
# 축하합니다!
# 남은 책은 9권 입니다.
# 축하합니다!
# 남은 책은 8권 입니다.
# 축하합니다!
# 남은 책은 7권 입니다.
# 축하합니다!
# 남은 책은 6권 입니다.
# 축하합니다!
# 남은 책은 5권 입니다.
# 축하합니다!
# 남은 책은 4권 입니다.
# 축하합니다!
# 남은 책은 3권 입니다.
# 축하합니다!
# 남은 책은 2권 입니다.
# 축하합니다!
# 남은 책은 1권 입니다.
# 축하합니다!
# 남은 책은 0권 입니다.
# 끝났습니다. 다음기회에!

11-3. Continue & Break

absent = [2, 5] #결석번호
no_book = [7] #책을 깜빡
for student in range(1, 11): # 출석번호 1~10번 까지 존재
    if student in absent:
        continue
    elif student in no_book:
        print("오늘 수업 여기까지. {0}은 교무실로 따라와".format(student))
        break
    print("{0}, 책을 읽어봐라.".format(student))

#"Continue"는 계속해서 다음 반복을 진행.
#"Break"은 지금 상황에서 바로 반복문을 종료하고 끝냄.

# 1, 책을 읽어봐라.
# 3, 책을 읽어봐라.
# 4, 책을 읽어봐라.
# 6, 책을 읽어봐라.
# 오늘 수업 여기까지. 7은 교무실로 따라와
profile
"Your goals, Minus your doubts, Equal your reality"

0개의 댓글