본문 바로가기
* Language/Python

[Python] 파이썬 반복문(for문, while문)

by codinguser 2020. 8. 30.

파이썬_반복문
출처 : Pixabay

[Python] 파이썬 반복문(for문, while문)

* 소스 코드 및 정리한 내용의 저작권은 글쓴이에게 있습니다.

 

파이썬 반복문(for문, while문)


1) 전체 구조?

 

1. while():

2. for i in range(n):

ㄴ for i in range(a, b):

ㄴ for i in range(a, b, 증감):

 

2) Why 사용?

 

"hello, python"을 10번 출력하고자 한다.
(외국어를 배울때 있어서도 그 나라의 "안녕" 이라는 말을 먼저 하기에 관습적으로 사용) 
가장 단순한건, print("hello, python")을 ctrl+c 해서 ctrl+v로 아래와 같이 10개를 만들면 된다. 

print("hello, python") 
print("hello, python") 
print("hello, python") 
print("hello python") 
print("hello python") 
print("hello python") 
print("hello python") 
print("hello python") 
print("hello python") 
print("hello python") 

하지만 이렇게 작성하는건 매우 비효율적이다. 왜 그런지는 본인이 100개 혹은 1000개 10000개를 복·붙을 해보면 알 것이다. 이와 같이 내가 입력하고자 하는 수에서 단계적으로 1000,10000 그 이상의 수로 사용하고자 할 때 효율적으로 사용하기 위해 반복문을 사용하게 된것이다.


3) How 사용?

 

(1)
while(조건문):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
i=0
while(i < 10):
    print(i)
    i = i + 1
    
# < 출력 결과 >
# 0   
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
cs

 

(2)

for i in range(n): # 0부터 10미만의 수를 i에 저장하겠다.

1
2
3
4
5
6
7
8
9
10
11
12
13
for i in range(10):
    print(i)
    
# < 출력 결과 >
# 0   
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
cs

 

ㄴ2-1)

for i in range(a, b): # a이상 b미만의 값을 i에 저장하겠다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for i in range(010):
    print(i)
    
# < 출력 결과>
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
cs

 

 

 

ㄴ2-2)

for i in range(a, b, 증감): # a이상 b미만의 값에서 i의 증감을 주겠다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for i in range(0202):
    print(i)
    
# < 출력 결과 >
# 0
# 2
# 4
# 6
# 8
# 10
# 12
# 14
# 16
# 18
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for i in range(200-2):
    print(i)
    
# < 출력 결과 >
# 20
# 18
# 16
# 14
# 12
# 10
# 8
# 6
# 4
# 2
cs

 


4) 예제코드

 

Hello, Python 10번 출력 예시

 

(1)

1
2
3
4
i=0
while i < 10:
    print("hello, python")
    i = i + 1
cs

 

(2)

 

1
2
for i in range(10):
    print("hello, python")
cs

 

 

(2-1)

 

1
2
for i in range(010):
    print("hello, python")
cs

 

 

(2-2)

 

1
2
for i in range(0202):
    print("hello, python")
cs

 

1
2
for i in range(200-2):
    print("hello, python")
cs

 


 

댓글