반복문과 조건문:
- 범위 경계 테스트를 반드시 한다.
- 예를 들어 range(4)로 지정했으면 print해서 값이 어떻게 나오는지 확인한다.
- 실무 측면에서 상황에 적합한 반복문을 활용하도록 한다.
- while문과 for문의 특징에 대해서 생각해본다.
# case 1 (반복문)
data = [90, 45, 32, 44]
for i in range(len(data)):
print(data[i]) # 90, 45, 32, 44
# case 2 (튜플 형태)
mock_data = {
"id": 1,
"first_name": "states",
"last_name": "code",
"email": "code@states.com",
"gender": "Female",
"ip_address": "123.123.123.23"
}
for x in mock_data:
print(x) # id, first_name, last_name, email, gender, ip_address
# case 3
mock_data = {
"id": 1,
"first_name": "states",
"last_name": "code",
"email": "code@states.com",
"gender": "Female",
"ip_address": "123.123.123.23"
}
for x in mock_data.keys(): keys 출력
print(x)
# case 4
mock_data = {
"id": 1,
"first_name": "states",
"last_name": "code",
"email": "code@states.com",
"gender": "Female",
"ip_address": "123.123.123.23"
}
for x in mock_data.values(): # values 출력
print(x)
# case 5
mock_data = {
"id": 1,
"first_name": "states",
"last_name": "code",
"email": "code@states.com",
"gender": "Female",
"ip_address": "123.123.123.23"
}
for x in mock_data.items():
print(x)
# ('id', 1)
# ('first_name', 'states')
# ('last_name', 'code')
# ('email', 'code@states.com')
# ('gender', 'Female')
# ('ip_address', '123.123.123.23')
for k,v in mock_data.items():
print(k,v)
# id 1
# first_name states
# last_name code
# email code@states.com
# gender Female
# ip_address 123.123.123.23
# 일반적인 반복문 활용
a = [1,2,3,4,5]
b = [10,20,30,40,50]
for i in range(len(a)):
print(a[i],b[i])
# 1 10
# 2 20
# 3 30
# 4 40
# 5 50
# zip 함수 활용
a = [1,2,3,4,5]
b = [10,20,30,40,50]
c = zip(a,b)
print(list(c))
# [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50)]
# 반복문과 zip 활용
a = [1,2,3,4,5]
b = [10,20,30,40,50]
c = [100,200,300,400,500]
for x,y,z in zip(a,b,c):
print(x,y,z)
# 1 10 100
# 2 20 200
# 3 30 300
# 4 40 400
# 5 50 500
# break
IntCollection=[0,1,2,3,4,5,6,7]
for x in IntCollection:
if(x==3):
break
else:
print(x)
# 0
# 1
# 2
# continue
IntCollection=[0,1,2,3,4,5,6,7]
for x in IntCollection:
if(x==3):
continue
else:
print(x)
# 0
# 1
# 2
# 4
# 5
# 6
# 7
# 반복문의 다양한 활용
list_ = [1,2,3,4,5]
def foo(list_):
print(list_)
print('foo(list_[i])')
for i in range(len(list_)):
foo(list_[i])
print('foo(element)')
for element in list_:
foo(element)
# foo(list_[i])
# 1
# 2
# 3
# 4
# 5
# foo(element)
# 1
# 2
# 3
# 4
# 5