๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
  • ์žฅ์›์ต ๊ธฐ์ˆ ๋ธ”๋กœ๊ทธ
๐Ÿคท๐Ÿผ‍โ™€๏ธ Etc.../- C, C++, Python, Android

Python ๋ฐ˜๋ณต๋ฌธ while ์ •๋ณตํ•˜๊ธฐ.

by Wonit 2019. 12. 6.

Python ๋ฐ˜๋ณต๋ฌธ while

ํŒŒ์ด์ฌ์€ ๋‹ค๋ฅธ ์–ธ์–ด์™€ ๋‹ฌ๋ฆฌ ๋ฐ˜๋ณต๋ฌธ์„ ๋ฐ˜๋ณต๊ณผ ์„ ํšŒ๋กœ ๋‚˜๋ˆˆ๋‹ค. while์€ ๋ฐ˜๋ณต๋ฌธ์ด๊ณ  for์€ ์ดํ„ฐ๋ ˆ์ด์…˜์„ ์‚ฌ์šฉํ•˜๋Š” ์„ ํšŒ์ธ๋ฐ, ๋ฐ”๋กœ ๋‹ค์Œ ๊ฐ•์˜๋ถ€ํ„ฐ for๋ฌธ์„ ๋ฐฐ์šฐ๋‹ˆ ๋ฐ˜๋ณต๋ถ„์„ ์ •๋ณตํ•˜๊ณ  ๋„˜์–ด๊ฐ€์ž.

 

while๋ฌธ ์‚ฌ์šฉํ•˜๊ธฐ.

 

while๋ฌธ์€ ํŠน์ • ์ฝ”๋“œ๋ฅผ loopํ•˜๊ธฐ ์œ„ํ•ด์„œ ์‚ฌ์šฉ๋œ๋‹ค. 1์—์„œ 5๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ฐ˜๋ณต๋ฌธ ์˜ˆ์ œ๋ฅผ ๋ณด์ž.

>>> count = 1
>>> while count <= 5:
...        print(count)
...        count+= 1
...
1
2
3
4
5
>>>

์ด๋ ‡๊ฒŒ ์ „์— ๋ฐฐ์šด if๋ฌธ์˜ ๋ฌธ๋ฒ•์ฒ˜๋Ÿผ :์„ ์‚ฌ์šฉํ•˜๊ณ  ๋“ค์—ฌ์“ฐ๊ธฐ๋˜ํ•œ ๋™์ผํ•˜๊ฒŒ ์ ์šฉ๋œ๋‹ค.

 

์ค‘๋‹จํ•˜๊ธฐ : break

break๋Š” ํŠน์ • ์กฐ๊ฑด์ด ๋งŒ์กฑํ•œ๋‹ค๋ฉด ๋ฐ˜๋ณต๋ฌธ์„ ๋น ์ ธ ๋‚˜๊ฐ€๋Š” ์—ญํ• ์„ ์ˆ˜ํ–‰ํ•œ๋‹ค. ๋ณดํ†ต if๋ฌธ๊ณผ ๋งŽ์ด ์“ฐ์ธ๋‹ค.

 

๋ฌธ์žฅ์˜ ์ฒซ ๊ธ€์ž๋ฅผ ๋Œ€๋ฌธ์ž๋กœ ๋ฐ”๊ฟ”์ฃผ๋Š” ํ”„๋กœ๊ทธ๋žจ
>>> while True:
...     simple_str = input('Input the character you want: ')
...     if simple_str == 'out':
...             break
...     else:
...             print(simple_str.capitalize())
...
Input the character you want: test
Test
Input the character you want: oh my god
Oh my god
Input the character you want: out
>>>

 

๊ฑด๋„ˆ๋›ฐ๊ธฐ : continue

continue๋Š” ๋ฐ˜๋ณต๋ฌธ์„ ์ค‘๋‹จํ•˜๊ณ  ์‹ถ์ง€๋Š” ์•Š์ง€๋งŒ ๋ช‡๋ช‡์˜ ์ด์œ ๋กœ ๋‹ค์Œ ๋ฃจํ”„๋กœ ๊ฑด๋„ˆ๋›ฐ๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

์ž…๋ ฅ ์ˆ˜๊ฐ€ ํ™€์ˆ˜๋ผ๋ฉด ๊ทธ ์ˆ˜์˜ ์ œ๊ณฑ์„, ์ง์ˆ˜์ผ ๋•Œ๋Š” ๋‹ค์Œ ๋ฃจํ”„๋กœ ์ง„ํ–‰ํ•˜๋Š” ์˜ˆ์ œ\
>>> while True:
...     value = input('input the number')
...     if value % 2 == 0:
...             continue
...     print(number, "์ œ๊ณฑ: ", number*number)
...
... input the number: 12
... input the number: 9
81
>>>

 

break ํ™•์ธํ•˜๊ธฐ : else

break๋Š” ์–ด๋–ค ๊ฒƒ์„ ์ฒดํฌํ•˜์—ฌ ๊ทธ๊ฒƒ์„ ๋ฐœ๊ฒฌํ–ˆ์„ ๊ฒฝ์šฐ ์ข…๋ฃŒํ•˜๋Š” while๋ฌธ์„ ์ž‘์„ฑํ•  ๋•Œ ์‚ฌ์šฉ๋˜๋Š”๋ฐ while๋ฌธ์ด ๋ชจ๋‘ ์‹คํ–‰๋˜์—ˆ์ง€๋งŒ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชป ํ•˜์˜€์„ ๋•Œ else๊ฐ€ ์‚ฌ์šฉ๋œ๋‹ค.

 

while๋ฌธ๊ณผ else์˜ ์กฐํ•ฉ์€ python์˜ ํŠน๋ณ„ํ•œ ๊ธฐ๋Šฅ์ด๋ผ๊ณ  ์ƒ๊ฐ๋˜๋Š”๋ฐ, ์šฐ๋ฆฌ๊ฐ€ ์ผ๋ฐ˜์ ์œผ๋กœ ๋ชจ๋‘ ์‹คํ–‰๋˜์—ˆ์ง€๋งŒ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชป ํ•˜์˜€์„ ๋•Œ๋Š” flag๊ฐ’์„ ์ง€์ •ํ•ด์ฃผ๋Š” ๋ฐฉ์‹์œผ๋กœ ์‚ฌ์šฉ๋˜์—ˆ๋‹ค. ํ•˜์ง€๋งŒ ๋ฌธ๋ฒ•์ ์œผ๋กœ python์€ ๊ฐ€๋Šฅํ•˜๊ฒŒ ํ•ด์ค€๋‹ค.

 

์˜ˆ์ œ
fruit = ['apple', 'mango', 'banana']
pos = 0
while pos < len(fruit):
    temp_fruit = fruit[pos]
    if temp_fruit == 'apeach':
        print('found')
        break
    pos += 1
else:
    print('not found')

์œ„๋Š” ํŒŒ์ด์ฐธ์˜ ์ˆœ์ˆ˜ ํŒŒ์ด์ฌ ์ธํ„ฐํ”„๋ฆฌํ„ฐ๋กœ ํ•ด์„๋œ ์†Œ์Šค์ฝ”๋“œ์ด๋‹ค.

 

while๊ณผ else์˜ ์กฐํ•ฉ์ด ์ด์ƒํ•˜๊ฒŒ ๋ณด์ผ ์ˆ˜๋„ ์žˆ์ง€๋งŒ, ๋‹จ์ง€ break ์ฒด์ปค๋ผ๊ณ  ์ƒ๊ฐํ•˜์ž.

๋Œ“๊ธ€