군침이 싹 도는 코딩
Python - for 루프 (리스트,딕셔너리 key,value,item) 본문
for문은 안에 있는 데이터를 어떠한 동작으로 반복하는 것이다.
score=[90,45,77,83,39]
new_list[]
for math in score :
print(math - 5)
new_list.append(math - 5)
>>> 85
40
72
78
34
new_list
>>> [85,40,72,78,34]
for 문은 변수 in 변수안에 넣을 데이터
그 후에 조건을 쓰는식으로 사용한다
for 문은 변수안에 넣을 데이터를 다 사용할때까지 반복한다
score라는 리스트에서 -5를 한 값을 new_list에 append 함수를 사용해 저장하였다.
이때 주의할점은 for문에서 임의로 사용한 math 라는 변수는 for문 밖에서는 사용해서는 안된다.
.
딕셔너리의 key 루프
my_phone={'brand':'apple','model':'iPhone 12', 'color':'red','year':2021}
for data in my_phone :
print(data.upper())
>>> BRAND
MODEL
COLOR
YEAR
어퍼 함수를 사용해서 딕셔너리의 키값을
전부 대문자로 출력하였다
딕셔너리의 value 루프
for data in my_phone.values() :
print(data)
>>> apple
iPhone 12
red
2021
.values 를 사용해 벨류값을 가져올수도 있다
key 와 value를 튜플로 루프
for data in my_phone.items() :
print(data)
>>> ('brand', 'apple')
('model', 'iPhone 12')
('color', 'red')
('year', 2021)
.items 를 사용해 키와 벨류 둘다 가져올 수 있다
for key , value in my_phone.items() :
print (key,value)
>>> brand apple
model iPhone 12
color red
year 2021
키와 벨류를 따로 가져올 수 도 있다
'Python > Basic' 카테고리의 다른 글
Python - range 함수 (0) | 2022.11.18 |
---|---|
Python - break (0) | 2022.11.18 |
Python 조건문 코드의 실행 순서 (0) | 2022.11.17 |
Python 조건문 - 연산자, and , or , if문 (0) | 2022.11.17 |
Python - Sets (add,discard) (0) | 2022.11.16 |