본문 바로가기

개발자 모드/파이썬(python)

파이썬 (python) for 반복문

728x90
# chapter 04_02
# 파이썬 반복문
# for 실습

# 코딩의 핵심
# for in <collection>
#  <loop body>

for v1 in range(10) : # 0~ 9
    print(v1)

print()
for v2 in range(1,11) :
    print(v2)

print()
for v3 in range(1,11,2)    :
    print(v3)


# 1 ~ 100 합

sum1 = 0

for v in range(1,101) :
    sum1  += v

print(sum1)

print(sum(range(1,101)))
print(sum(range(4,1001,4)))



# iterables 자료형 반복
# 문자열, 리스트, 듀플, 집합, 사전
# iterables 리턴 함수 : range reversed map zip ~

# 예제

names =['kim','park','lee','cho']

for n in names :
    print(n)

print()

# 예제
lotto_numbers =[11,19,21,28,36,37]

for n in lotto_numbers :
    print(n)

word ="beautiful"

for n in word :
    print(n)


print()

my_info ={
    "name": 'lee',
    "age" : 33,
    "city":"seoul"
}

for k in my_info :
    print(k)

print()

for key in my_info :
    print(my_info[key])

print()

for v in my_info.values() :
    print(v)

print()

for v in my_info.items() :
        print(v)

# 예제

name ="FineApple"

for n in name :
    if n.isupper() :
        print(n)
    else :
        print(n.upper())



# break


numbers = [14,3,4,7,10,24,17,2,33,15,34,36,38]

for num in numbers :
    if num == 34 :
        print('found', num)
        break;
    else :
        print('not found', num)

print()

# continue

lt = ["1",2,5, True, 4.3, complex(4)]

for v in lt :
    if type(v) is bool :
        continue  # 일종의 skip 기능이라고 볼수 있다.
    print(v * 3)
    print(type(v))



# for - else


numbers = [14,3,4,7,10,24,17,2,33,15,34,36,38]

for num in numbers :
    if num == 55:
        print('found')
        break
else :
        print('not found : 55')


# 구구단

for i in range(2,10) :
    for j in range (1,10) :
        print( '{:4d}'.format(i*j), end='' )
    print()





 

결과

 

[Command: python -u C:\python_basic\chapter04_02.py]
0
1
2
3
4
5
6
7
8
9

1
2
3
4
5
6
7
8
9
10

1
3
5
7
9
5050
5050
125500
kim
park
lee
cho

11
19
21
28
36
37
b
e
a
u
t
i
f
u
l

name
age
city

lee
33
seoul

lee
33
seoul

('name', 'lee')
('age', 33)
('city', 'seoul')
F
I
N
E
A
P
P
L
E
not found 14
not found 3
not found 4
not found 7
not found 10
not found 24
not found 17
not found 2
not found 33
not found 15
found 34

111
<class 'str'>
6
<class 'int'>
15
<class 'int'>
12.899999999999999
<class 'float'>
(12+0j)
<class 'complex'>
not found : 55
   2   4   6   8  10  12  14  16  18
   3   6   9  12  15  18  21  24  27
   4   8  12  16  20  24  28  32  36
   5  10  15  20  25  30  35  40  45
   6  12  18  24  30  36  42  48  54
   7  14  21  28  35  42  49  56  63
   8  16  24  32  40  48  56  64  72
   9  18  27  36  45  54  63  72  81
[Finished in 0.131s]

728x90