Python
[Python] 파이썬 반복문
코린이예요
2018. 9. 13. 16:47
반응형
# 1. for 문
# 문자열에 들어올 수 있는 요소 ; 문자열,리스트,튜플,사전,집합,바이트형태 문자열
# 조건 끝나면 ":를 붙인다.
1 2 3 | for entry in "Hello Apple": print(entry) pass | cs |
결과 화면
1 2 3 4 5 6 7 8 9 10 11 | H e l l o A p p l e | cs |
# 사전 for문 example
1 2 | for entry in {'a' : 'A', 'b' : 'B'}: print(entry) | cs |
결과 화면
1 2 | a b | cs |
entry에 key만 가져와진다.
1 2 | for entry in {'a': 'A', 'b': 'B'}.values(): print(entry) | cs |
결과 화면
1 2 | A B | cs |
entry에 value 만 가져와짐
1 2 | for entry in {'a': 'A', 'b': 'B'}.items(): print(entry) | cs |
결과 화면
1 2 | ('a', 'A') ('b', 'B') | cs |
key value 쌍으로 가져와짐 (패킹)
# 언패킹 개념으로 아래와 같이 나타낼수 있다.
1 2 3 | for key, value in {'a': 'A', 'b': 'B'}.items(): print(key) print(value) | cs |
결과 화면
1 2 3 4 | a A b B | cs |
# break
1 2 3 | for key, value in {'a': 'A', 'b': 'B'}.items(): if key == 'a': break | cs |
# 처리를 안하고 for문을 나오고 싶을 경우
# continue
조건문을 수행하지 않고 건너 뛴다.
1 2 3 4 5 | for key, value in {'a': 'A', 'b': 'B'}.items(): if key == 'a': continue else: print("거짓") | cs |
# 2. while문
1 2 3 | a = 1 while a: pass | cs |
1 2 3 4 | num = 1 while num <= 100: print(num) num = num + 1 | cs |
반응형