08. Python Basics - 반복문(for, while)

Jayson Hwang·2022년 4월 5일
0

Python Basics

목록 보기
8/10

8-(1) 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).

for 예제

# print("waiting no. : 1")
# print("waiting no. : 2")
# print("waiting no. : 3")
# print("waiting no. : 4")

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

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
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.

8-(2) while(반복문)

  • for과 동일한 기능
  • but, for문은 이터레이터를 이용하여 반복문 기능을 수행
  • while문은 조건이 "참"인 동안 내부의 실행문들을 반복 실행
  • 특정 조건을 만족하는 동안 해당 코드들을 반복
num = 0 # num이 0부터 시작
while num <= 5: # num이 5보다 작거나 같을때 까지
    print(num) # num을 출력해라
    num += 1 # 그 후 num에 1을 더해라
    
#0
#1
#2
#3
#4
#5

while 예제

ex1) 까페에서 손님을 다섯번 부르고, 찾으러오지 않으면 커피 폐기처분

customer = "Thor"
index = 5
while index >= 1:
    print("{0}, your coffee is here. {1} left.".format(customer, index))
    index -= 1
    if index == 0:
        print("your coffee is discarded.")

# Thor, your coffee is here. 5 left.
# Thor, your coffee is here. 4 left.
# Thor, your coffee is here. 3 left.
# Thor, your coffee is here. 2 left.
# Thor, your coffee is here. 1 left.
# your coffee is discarded.
ex2) 무한 루프

customer = "Thor"
index = 1
while True:
    print("{0}, your coffee is here. {1}times called.".format(customer, index))
    index += 1
    
# 무한정으로 호출을 계속함
# **CTRL + C 누르면 강제 종료**
ex3) 원하는 값이 input될 때까지 계속 진행, 원하는 input값이 입력되면 종료

customer = "Thor"
person = "Unknown"

while person != customer:
    print("{0}, your coffee is here.".format(customer))
    person = input("What is your name? ")

# Thor, your coffee is here.
# What is your name? iron
# Thor, your coffee is here.
# What is your name? thor
# Thor, your coffee is here.
# What is your name? Thor
# 종료(반복문 탈출)

8-(3) Continue & Break

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

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

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권 입니다.
# 끝났습니다. 다음기회에!

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은 교무실로 따라와

8-(4) 한줄로 끝내는 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']
----------------------------------
profile
"Your goals, Minus your doubts, Equal your reality"

0개의 댓글