TIL 19 | python, for, while 반복문

ryan·2020년 8월 3일
1

Python

목록 보기
8/18

반복문

대부분의 프로그래밍 언어에서는 반복되는 작업을 간단하게 처리하기 위해 반복문이라는 기능을 제공해준다. 반복문은 반복 횟수, 반복 및 정지 조건을 자유자재로 제어할 수 있다.

for와 range 사용하기

for 변수 in range(횟수):
	반복할 코드

'Hello, world!'를 100번 출력해보자

cnt = 1
for i in range(100):
	print('Hello, world {0}'.format(cnt))
	cnt += 1
    
Hello, world 1
Hello, world 2
Hello, world 3
Hello, world 4
Hello, world 5
Hello, world 6
... (생략)
Hello, world 95
Hello, world 96
Hello, world 97
Hello, world 98
Hello, world 99
Hello, world 100
  • for 반복문은 횟수가 정해져 있을 때 주로 사용한다.
  • for 변수 in range(횟수) -> 반복할 코드로 순환하는 것을 루프(loop)라고 부른다.

반복문의 변수 i를 루프 인덱스라고 부르며 index의 첫 머리글자를 따서 i를 주로 사용한다.

for와 range 응용하기

시작하는 숫자와 끝나는 숫자를 지정해서 반복해보자

  • for 변수 in range(시작, 끝):
for i in range(5, 50):	#5부터 49까지 반복
    print('Hello, python!', i)

Hello, python! 5
Hello, python! 6
Hello, python! 7
Hello, python! 8
... 생략
Hello, python! 46
Hello, python! 47
Hello, python! 48
Hello, python! 49

증가폭 사용하기

range는 증가폭을 지정하면 해당 값만큼 숫자를 증가시킬 수 있다.

  • for 변수 in range(시작, 끝, 증가폭):

0부터 100까지의 숫자 중 짝수만 출력해보자

for i in range(0, 101, 2):
    print('This is even time!', i)

This is even time! 0
This is even time! 2
This is even time! 4
This is even time! 6
... 생략
This is even time! 94
This is even time! 96
This is even time! 98
This is even time! 100

숫자를 감소시켜보자

for i in range(10, 0): #range(10, 0)은 동작하지 않음
	print("I'm decreasing!!!", i) 

for i in range(10, 0, -1):
    print('I\'m decreasing!!!', i)

I'm decreasing!!! 10
I'm decreasing!!! 9
I'm decreasing!!! 8
I'm decreasing!!! 7
I'm decreasing!!! 6
I'm decreasing!!! 5
I'm decreasing!!! 4
I'm decreasing!!! 3
I'm decreasing!!! 2
I'm decreasing!!! 1

증가폭을 음수로 지정하는 방법 말고도 reversed를 사용하면 숫자의 순서를 반대로 뒤집을 수 있다.

  • for 변수 in reversed(range(횟수))
  • for 변수 in reversed(range(시작, 끝))
  • for 변수 in reversed(range(시작, 끝, 증가폭))
for i in reversed(range(10)):
    print('Ok, bye', i)

Ok, bye 9
Ok, bye 8
Ok, bye 7
Ok, bye 6
Ok, bye 5
Ok, bye 4
Ok, bye 3
Ok, bye 2
Ok, bye 1
Ok, bye 0

변수 i는 반복할 때마다 다음 값으로 덮어써지기 때문에 값을 할당해도 변수에 영향을 주지 못한다.

입력한 횟수대로 반복해보자

count = int(input('반복할 횟수를 입력하세요: '))

for i in range(count):
	print('Hello, python', i)
    
반복할 횟수를 입력하세요: 2
Hello, world! 0
Hello, world! 1
count = int(input('반복할 횟수를 입력하세요: '))

if 0 < count < 100:
    for i in range(count):
        print('시리야')
        print('안녕하세요, 뼈가 시려요', i)
else:
    print('잘못 입력하였습니다. 1부터 99까지 입력해주세요.')
    
    
반복할 횟수를 입력하세요: 5
시리야
안녕하세요, 뼈가 시려요 0
시리야
안녕하세요, 뼈가 시려요 1
시리야
안녕하세요, 뼈가 시려요 2
시리야
안녕하세요, 뼈가 시려요 3
시리야
안녕하세요, 뼈가 시려요 4

시퀀스 객체로 반복하기

for에 range 대신 리스트, 튜플, 문자열 등 시퀀스 객체로 반복할 수 있다.

# 리스트
a = [1, 2, 3, 4, 5]

for i in a:
    print(i)

1
2
3
4
5

for 반복문의 변수를 i 대신 flavor로 사용하듯이, for에서 변수 i는 다른 이름으로 만들어도 상관없다.

# 튜플
iceCream = ('strawberry', 'chocolate', 'vanila')


for flavor in iceCream:
    print(flavor)

strawberry
chocolate
vanila

for에 문자열을 지정하면 문자를 하나씩 꺼내면서 반복한다.

for letter in 'Developer':
    print(letter, end=' ')

D e v e l o p e r 

문자열을 뒤집어서 문자를 출력하려면 reversed를 활용하자.

for letter in reversed('Developer'):
    print(letter, end=' ')

r e p o l e v e D 

for 반복문은 반복 개수가 정해져 있을 때 주로 사용한다. for 반복문은 range 이외에도 시퀀스 객체를 사용할 수 있다.

구구단 출력

값 여러개 출력

  • print(값1, 값2, 값3)
  • print(변수1, 변수2, 변수3)
multi = int(input('숫자를 입력하세요: '))

for i in range(1, 10):
    print(multi, '*', i, '=', multi * i)
    
    
숫자를 입력하세요: 5
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45

while 반복문 사용하기

while 반복문은 조건식으로만 동작하며 반복할 코드 안에 조건식에 영향을 주는 변화식이 들어간다.

i = 0		# 초기식
while i < 100:		# while 조건식
    print('Hello, I\'m while loop!', i)		# 반복할 코드
    i += 1		# 변화식

Hello, I'm while loop! 0
Hello, I'm while loop! 1
Hello, I'm while loop! 2
Hello, I'm while loop! 3
...생략
Hello, I'm while loop! 97
Hello, I'm while loop! 98
Hello, I'm while loop! 99

while 반복은 초기식부터 시작해서 조건식을 판별한다. 이때 조건식이 참(True)이면 반복할 코드와 변화식을 함께 수행한다. 그리고 다시 조건식을 판별하여 참(True)이면 코드를 계속 반복하고, 거짓(False)이면 반복문을 끝낸 뒤 다음 코드를 실행한다.

조건식 -> 반복할 코드 및 변화식 -> 조건식으로 순환하는 부분이 루프(loop)이다.

while 반복문 사용하기

초기식
while 조건식:
	반복할 코드		# while 다음 줄 코드는 반드시 들여쓰기 하기!
    변화식
i = 0
while i < 100:
    print('Hello, python')
    i += 1
    
Hello, python
Hello, python
Hello, python
Hello, python
...생략
Hello, python
Hello, python

while 반복문은 반복할 코드 안에 변화식을 지정해야 한다. 만약 조건식만 지정하고 변화식을 생략하면 반복이 끝나지 않고 계속 실행(무한 루프)되므로 주의해야 한다.

초깃값을 1부터 시작해보자

i = 1
while i <= 100:
    print('Hello, python', i)
    i += 1

Hello, python 1
Hello, python 2
Hello, python 3
...생략
Hello, python 98
Hello, python 99
Hello, python 100

i가 1부터 100까지 증가하면서 100번 반복하게 되다가, i가 101이 되면 i <= 100은 거짓(False)이므로 반복문을 끝낸다.

초깃값을 감소시켜보자

초깃값을 크게 주고, 변수를 감소시키면서 반복할 수도 있다.

i = 100
while i > 0:
    print('Hello, python', i)
    i -= 1

Hello, python 100
Hello, python 99
Hello, python 98
...생략
Hello, python 3
Hello, python 2
Hello, python 1

입력한 횟수대로 반복해보자

# 입력한 횟수대로 반복

count = int(input('반복할 횟수를 입력하세요: '))

i = 0
while i < count:
    print('Hello, python!', i)
    i += 1

반복할 횟수를 입력하세요: 5
Hello, python! 0
Hello, python! 1
Hello, python! 2
Hello, python! 3
Hello, python! 4
# 초깃값만큼 출력
count = int(input('반복할 횟수를 입력하세요: '))

while count > 0:
    print('Hello, python!', count)
    count -= 1

반복할 횟수를 입력하세요: 5
Hello, python! 5
Hello, python! 4
Hello, python! 3
Hello, python! 2
Hello, python! 1

반복 횟수가 정해지지 않은 경우

while 반복문은 반복 횟수가 정해지지 않았을 때 주로 사용한다. 난수를 생성해서 숫자에 따라 반복을 끝내보자. 난수(random number)란 특정 주기로 반복되지 않으며 규칙 없이 무작위로 나열되는 숫자를 뜻한다.

파이썬에서 난수를 생성하려면 random 모듈이 필요하다.

  • import 모듈
import random		# random 모듈을 가져온다

random.random()으로 random 모듈의 random 함수를 호출해보자

>>> import random

>>> random.random()
0.7205279462911864
>>> random.random()
0.510094494980832
>>> random.random()
0.678860346653201

정수를 생성하는 random 모듈의 randint 함수를 사용해보자

  • random.randint(a, b)
  • randint 함수로 주사위 만들기
random.randint(1, 6)	# 1과 6 사이의 난수 생성

>>> random.randint(1, 6)
4
>>> random.randint(1, 6)
5
>>> random.randint(1, 6)
1

while 반복문에 사용해보기

3이 나올 때까지 주사위를 계속 던지는 while 반복문을 작성해보자

import random	# random 모듈을 가져오기

i = 0
while i != 3:	# 3이 아닐 때 계속 반복
    i = random.randint(1, 6)	# randint를 사용해서 1과 6사이의 난수 생성
    print(i)

1
6
5
4
5
6
5
2
3

while 반복문은 반복 횟수가 정해져 있지 않을 때 유용하다.

while 반복문으로 무한 루프를 만들어보자

while True:
    print('while에 True를 지정하면 무한 루프야.')
    print('Ctrl + C를 눌러서 무한 루프에서 벗어나!')

while에 True 대신 True로 취급하는 값을 사용해도 무한 루프로 동작한다.

while 1:
	print('0이 아닌 숫자는 True! 무한 루프!')

while 'Python':
	print('내용이 있는 문자열은 True! 무한 루프!')
    

while 반복문은 반봇 횟수가 정해져 있지 않을 때 자주 사용하고, for 반복문은 반복 횟수가 정해져 있을 때 자주 사용한다.

while 반복문 문제 중에 교통카드 사용했을 때 잔액을 각 줄에 출력하는 프로그램을 만드는 게 있었는데, 코드 답안과 다르게 내 코드는 한 줄이 더 있고, 좀 지저분한 느낌... 클린 코드, 클린 코드, 클린 코드를 하자. 좋은 코드들을 자주 보자.

오늘 공부 정리

  • for, while 반복문
profile
👨🏻‍💻☕️ 🎹🎵 🐰🎶 🛫📷

0개의 댓글