반응형
이번 시간에는 파이썬의 반복문 대해서 알아보는 시간을 갖겠다.
1. for 문
- for문에 사용가능한 자료형 : 문자열, 리스트, 튜플, 집합, 사전
- for문에 사용가능한 함수 : range, reversed, enumerate, filter, map, zip
기본 예제 1
for a1 in range(5):
print("a1 is :", a1)
Result
a1 is : 0
a1 is : 1
a1 is : 2
a1 is : 3
a1 is : 4
기본 예제 2
for a2 in range(1, 6):
print("a2 is :", a2)
Result
a2 is : 1
a2 is : 2
a2 is : 3
a2 is : 4
a2 is : 5
기본 예제 3
for a3 in range(1, 6, 2):
print("a3 is :", a3)
Result
a3 is : 1
a3 is : 3
a3 is : 5
① 예제 1
names = ["Kim", "Park", "Cho", "Lee", "Choi", "Yoo"]
for name in names:
print("You are", name)
Result
You are Kim
You are Park
You are Cho
You are Lee
You are Choi
You are Yoo
② 예제 2
lotto_numbers = [11, 19, 21, 28, 36, 37]
for number in lotto_numbers:
print("Your number", number)
Result
Your number 11
Your number 19
Your number 21
Your number 28
Your number 36
Your number 37
③ 예제 3
word = 'dreams'
for s in word:
print('word : ', s)
Result
word : d
word : r
word : e
word : a
word : m
word : s
④ 예제 4
my_info = {
"name": "Kim",
"age": 33,
"city": "Seoul"
}
for key in my_info:
print(key, ":", my_info[key])
for val in my_info.values():
print(val)
Result
name : Kim
age : 33
city : Seoul
Kim
33
Seoul
⑤ 예제 5
name = 'KennRY'
for n in name:
if n.isupper():
print(n)
else:
print(n.upper())
numbers = [14, 3, 4, 7, 10, 24, 17, 2, 33, 15, 34, 36, 38]
Result
K
E
N
N
R
Y
⑥ break 문
numbers = [14, 3, 4, 7, 10, 24, 17, 2, 33, 15, 34, 36, 38]
for num in numbers:
if num == 33:
print("found : 33!")
break
else:
print("not found : ", num)
Result
not found : 14
not found : 3
not found : 4
not found : 7
not found : 10
not found : 24
not found : 17
not found : 2
found : 33!
⑦ continue 문
lt = ["1", 2, 5, True, 4.3, complex(4)]
for v in lt:
if type(v) is float:
continue
print("type:", type(v))
print("multiply by 2:", v * 3)
Result
type: <class 'str'>
multiply by 2: 111
type: <class 'int'>
multiply by 2: 6
type: <class 'int'>
multiply by 2: 15
type: <class 'bool'>
multiply by 2: 3
type: <class 'complex'>
multiply by 2: (12+0j)
⑧ for else 문
- else 구문 : 반복문이 정상적으로 수행 된 경우 else 블럭 수행 (break로 나오면 실행 안함)
numbers = [14, 3, 4, 7, 10, 24, 17, 2, 33, 15, 34, 36, 38]
for num in numbers:
if num == 33: # 45
print("found : 33!")
break
else:
print("not found : ", num)
else:
print("Not Found 39...")
Result
not found : 14
not found : 3
not found : 4
not found : 7
not found : 10
not found : 24
not found : 17
not found : 2
found : 33!
⑨ 중첩 for 문
for i in range(1, 11):
for j in range(1, 11):
print('{:4d}'.format(i * j), end='')
Result
not found : 14
not found : 3
not found : 4
not found : 7
not found : 10
not found : 24
not found : 17
not found : 2
found : 33!
반응형
'Programming > Python' 카테고리의 다른 글
[Python] 파이썬 람다(Lambda)에 대해서 알아보자. (0) | 2021.06.20 |
---|---|
[Python] 파이썬 함수에 대해서 알아보자. (0) | 2021.06.20 |
[Python] 파이썬 반복문에 대해서 알아보자. (while문) (0) | 2021.06.03 |
[Python] 파이썬 조건문에 대해서 알아보자. (if문, 관계 연산자, 논리 연산자) (0) | 2021.05.17 |
[Python] 파이썬 가상환경 설정 및 패키지 설치에 대해서 알아보자. (0) | 2021.05.11 |