제어문(Control Statements)
1. 기본 사용법
파이썬에도 if, for, while이 있다. 특히 파이썬은 자료구조형과 밀접하게 연계되어 자료구조에 들어있는 자료들에 대해 쉽게 제어문을 실행할 수 있다. 기본 사용법은 다음과 같다.
if condition1:
statements_when_condition1_is_true
elif condition2:
statements_when_condition2_is_true
else:
statements_when_no_condition_is_true
for elem in something_iterable:
statements_to_process_elem
while condition:
statements_while_condition_is_true
이를 토대로 동물 친구들을 다시 데려와서 예제를 만들어보겠다.
mammal = ["dog", "cat", "lion", "tiger"]
reptile = ["snake","turtle", "lizard", "frog"]
mypet = "turtle"
if mypet in mammal:
print(f"{mypet}: my pet is mammal")
elif mypet in reptile:
print(f"{mypet}: my pet is reptile")
else:
print(f"{mypet}: what..?")
print("anti-pythonic for loop")
for i in range(len(reptile)):
print(f"{i}) {reptile[i]}")
print("pythonic for loop")
for ma in mammal:
print(f" {ma}")
i = 0
print("reptiles whose name ends with 'e'")
while i < len(reptile) and reptile[i].endswith('e'):
print(f" {reptile[i]}")
i += 1
출력 :
turtle: my pet is reptile
anti-pythonic for loop
0) snake
1) turtle
2) lizard
3) frog
pythonic for loop
dog
cat
lion
tiger
reptiles whose name ends with 'e'
snake
turtle
2. 반복문 제어
반복문을 돌리다 보면 조건에 따라 중간 처리를 건너뛰고 싶거나 반복문을 종료하고 싶을 때가 있다. continue는 반복문에서 continue 이후의 과정을 건너뛰고 다음 loop로 넘어가는 것이고, break는 반복문 자체를 끝낸다.
mammal = ["dog", "cat", "lion", "tiger"]
reptile = ["snake","turtle", "lizard", "frog"]
print("list of mammal")
for ma in mammal:
if ma.startswith("dog"):
print(" wal! wal!")
continue
if ma.startswith("cat"):
print(" nyaong~")
break
print(f" {ma} is cool")
name = None
print("Press 'q' to quit")
while name != 'q':
print("type reptile's name")
name = input()
if name == 'q':
break
if name not in reptile:
print(f"{name} is not reptile")
continue
index = reptile.index(name)
print(f"{name}'s index =", index)
3. enumuerate, zip
파이썬에서는 while 보다 for문의 활용법이 다양하다. 대표적으로 enumerate, zip이 있다.
enumerate는 for문에서 리스트를 반복할 시 원소 뿐만 아니라 인덱스도 받을 수 있는 튜플 반복 객체를 만들어 준다. zip은 두 개의 리스트를 묶어서 각 리스트의 원소가 하나씩 합쳐진 튜플 반복 객체를 만들어준다.
이들을 리스트로 변환해보면 무엇을 주는지 명확히 볼 수 있다.
mammal = ["dog", "cat", "lion", "tiger"]
reptile = ["snake","turtle", "lizard", "frog"]
print("what does enumerate() return?", enumerate(mammal))
print(list(enumerate(mammal)))
print("what does zip() return?", zip(mammal, reptile))
print(list(zip(mammal, reptile)))
print("print only odd-order mammal with index")
for index, name in enumerate(mammal):
if index % 2 == 0:
continue
print("mammal:", index, name)
print("print pairs of mammal and reptile")
for ma, re in zip(mammal, reptile):
print(f"{ma} and {re}")
출력 :
what does enumerate() return? <enumerate object at 0x0000025D5D81E980>
[(0, 'dog'), (1, 'cat'), (2, 'lion'), (3, 'tiger')]
what does zip() return? <zip object at 0x0000025D5D86E580>
[('dog', 'snake'), ('cat', 'turtle'), ('lion', 'lizard'), ('tiger', 'frog')]
print only odd-order mammal with index
mammal: 1 cat
mammal: 3 tiger
print pairs of mammal and reptile
dog and snake
cat and turtle
lion and lizard
tiger and frog
4. Iterate over Dict
딕셔너리 또한 반복문에 자주 사용된다. 딕셔너리는 Key와 Value가 있기에 필요에 따라 for문에 들어가느 객체가 달라진다.
Key만 사용 : dict 객체 자체, keys()함수
Value만 사용 : values() 함수
둘 다 사용 : items() 함수
animal = {"pooh": "bear", "tigger": "tiger"}
print("iterate over Dictionary KEYS")
for character in animal:
print("character:", character)
for character in animal.keys():
print("character:", character)
print("iterate over Dictionary VALUES")
for species in animal.values():
print("species:", species)
print("iterate over Dictionary ITEMS")
for character, species in animal.items():
print(f"character:species = {character}:{species}")
출력 :
iterate over Dictionary KEYS
character: pooh
character: tigger
character: pooh
character: tigger
iterate over Dictionary VALUES
species: bear
species: tiger
iterate over Dictionary ITEMS
character:species = pooh:bear
character:species = tigger:tiger
5. List Comprehension
리스트를 다루다 보면 다른 리스트에 기반해서 새로운 리스트를 만들거나 기존 리스트에 필요한 것만 걸러서 새로운 리스트를 만들고 싶을 때가 있다.
기존 방식으론 다음과 같이 구현할 수 있는 예제가 있다.
reptile = ["snake","turtle", "lizard", "frog"]
print("create a modified list from the existing list")
cool_reptile = []
for hero in reptile:
cool_reptile.append(hero + "_cool")
print("cool reptiles :", cool_reptile)
print("extract a subset of the existing list")
man_heroes = []
for hero in reptile:
if hero.endswith("e"):
man_heroes.append(hero)
print("end with 'e' :", man_heroes)
출력 :
create a modified list from the existing list
cool reptiles : ['snake_cool', 'turtle_cool', 'lizard_cool', 'frog_cool']
extract a subset of the existing list
end with 'e' : ['snake', 'turtle']
하는 일에 비해 여러 줄을 차지한다. 파이썬에는 리스트를 선언하는 [] 안에 for문을 넣어 for문을 한 줄로 처리하는 list comprehension이란 방법이 있다.
reptile = ["snake","turtle", "lizard", "frog"]
print("square of integers")
int_square = [i ** 2 for i in range(10)]
print(int_square)
print("create a modified list by list comprehension")
cool_reptiles = [rep + "_cool" for rep in reptile]
print("cool reptiles", cool_reptiles)
print("extract a subset by list comprehension")
rep = [rep for rep in reptile if rep.endswith("e")]
print("end with 'e':", rep)
출력 :
square of integers
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
create a modified list by list comprehension
cool reptiles ['snake_cool', 'turtle_cool', 'lizard_cool', 'frog_cool']
extract a subset by list comprehension
end with 'e': ['snake', 'turtle']
간단한 처리과정을 넣어 다양하게 쓰일 수 있고 다중 for문이 들어갈 수도 있다. 이러한 기능을 list만 쓸 수 있는 건 아니고 dictionary와 set에도 적용될 수 있다.
animal = ["cow","chicken", "dog", "cat"]
print("dictionary comprehension")
sounds = ["음머~", "꼬끼오~", "월!월!", "냐옹~"]
animals = {name: sound for name, sound in zip(animal, sounds)}
print("animal's sound:", animals)
출력 :
dictionary comprehension
animal's sound: {'cow': '음머~', 'chicken': '꼬끼오~', 'dog': '월!월!', 'cat': '냐옹~'}
'학부 생활 + 랩실 > Python' 카테고리의 다른 글
| 파이썬(7) - 패키지 (0) | 2026.04.04 |
|---|---|
| 파이썬(6) - 함수 (0) | 2026.04.04 |
| 파이썬(4) - 컨테이너(2) 딕셔너리, 튜플 (0) | 2026.04.03 |
| 파이썬(3) - 컨테이너(1) 리스트 (1) | 2026.04.03 |
| 파이썬(2) - 문자열 타입 (0) | 2026.04.02 |