데이터 분석/파이썬
[파이썬] 7. 제어문 & 반복문 (for문, while문)
행복한 댕글
2021. 4. 13. 23:15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
|
# Day_02_01_loop.py
# count= input('count : ')
# print('Good morning!')
# 문제
# count에 0~3 사이의 숫자를 입력 받아서
# 입력 받은 숫자만큼 아침 인사를 해봅니다.
# 2가지 종류의 코드를 만들어 봅니다.
def not_used_1():
count= int(input('count : '))
if count == 1:
print('Good morning!')
elif count == 2:
print('Good morning!')
print('Good morning!')
elif count == 3:
print('Good morning!')
print('Good morning!')
print('Good morning!')
count = 2
if count > 0:
print('Good morning!')
count = count-1
if count > 0:
print('Good morning!')
count = count-1
if count > 0:
print('Good morning!')
count = count-1
count = 3
if count > 0:
print('Good morning!')
count -= 1
if count > 0:
print('Good morning!')
count -= 1
if count > 0:
print('Good morning!')
count -= 1
count = 2
i = 0
if i < count:
print('Good morning!')
i += 1
if i < count:
print('Good morning!')
i += 1
if i < count:
print('Good morning!')
i += 1
if i < count:
print('Good morning!')
i += 1
if i < count:
print('Good morning!')
i += 1
# while문의 뜻: 참 or 거짓일 때까지 반복한다.
count = 2
i = 0
while i < count:
print('Good morning!')
i += 1
# 규칙 (반복문은 규칙을 잘 찾아야 한다.)
# 1 3 4 7 9 1, 9, 2 (1에서 9까지의 숫자 중 2칸씩 건너뛴다.)
# 0 1 2 3 4 0, 4, 1 (0에서 4까지 가는데 1칸씩 건너뛴다.)
# 5 4 3 2 1 5, 1 , -1 (5에서 1까지 가는데 -1씩 건너뛴다.)
i = 1 # 시작
while i <= 9: # 종료
print('hello')
i += 2 # 증감
i = 0 # 시작
while i <= 4: # 종료
print('hello')
i += 1 # 증감
i = 5 # 시작
while i >= 1: # 종료
print('hello')
i -= 1 # 증감
# 문제
# 0~99까지 출력하는 함수를 만드세요.
# 0~99까지 한 줄에 10개씩 출력하는 함수를 만드세요. (규칙을 찾아야함)
# print('hello', end='')
# print('python')
# 방법 1 : 일렬 (ex. 0 1 2 3 4 ...)
def show100(): # 0, 99, 1
i = 0
while i < 100: # 99보다 100이 더 좋음 -> 100개니까
print(i, end=' ')
i += 1
show100()
# 방법 2 : 10개씩 정렬
# 0 1 2 3 4 5 6 7 8 9
# 10 11 12 13 14 15 16 17 18 19
# 20 21 22 23 24 25 26 27 28 29
# 30 31 32 33 34 35 36 37 38 39
# 40 41 42 43 44 45 46 47 48 49
# 50 51 52 53 54 55 56 57 58 59
# 60 61 62 63 64 65 66 67 68 69
# 70 71 72 73 74 75 76 77 78 79
# 80 81 82 83 84 85 86 87 88 89
# 90 91 92 93 94 95 96 97 98 99
def show100():
i = 0
while i < 100:
print(i, end=' ')
if i%10 == 9:
print()
i += 1
# not good
# i = 0
# while i < 100:
# print(i, end=' ')
# i += 1
# if i % 10 == 0: (증감에 관련된 코드는 맨 밑에)
# print()
show100()
|
cs |
· 파이썬은 switch문이 없어서 if문으로 모두 처리 → 장점: 문법이 단순함
· for문을 사용할 수 없을 때 while문 사용 (10번 중 2번 정도)