[Python] for-else / while-else ๋ฌธ

ํ† ๋ผ๋Š” ๊ฐœ๋ฐœ๊ฐœ๋ฐœยท2021๋…„ 12์›” 27์ผ
0

Python

๋ชฉ๋ก ๋ณด๊ธฐ
6/11
post-thumbnail
post-custom-banner

โœ๏ธ for-else / while-else๋ฌธ

๐Ÿ‘‰๐Ÿป ๋‹ค๋ฅธ ์–ธ์–ด์™€ ๋‹ค๋ฅด๊ฒŒ ํŒŒ์ด์ฌ์— ์žˆ๋Š” ๋ฌธ๋ฒ•์œผ๋กœ, ๋ฐ˜๋ณต๋ฌธ(for/while) ๋„์ค‘ break๊ฐ€ ๋˜์ง€ ์•Š๊ณ  ๋๊นŒ์ง€ ๋ฐ˜๋ณต์„ ์‹คํ–‰ํ–ˆ์„ ๊ฒฝ์šฐ else์— ์žˆ๋Š” ์ฝ”๋“œ๋ฅผ ์‹คํ–‰ํ•˜๊ฒŒ๋” ํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

์ฆ‰, ๋ฐ˜๋ณต๋ฌธ์ด ๋ฉˆ์ถ”์ง€ ์•Š๊ณ  ์ „๋ถ€ ์‹คํ–‰ํ–ˆ์„ ๊ฒฝ์šฐ ์‹คํ–‰ํ•  ์ฝ”๋“œ๋“ค์„ ์ ๋Š”๋‹ค.


โœจ ๋‹ค์Œ ์˜ˆ์‹œ๋ฅผ ์‚ดํŽด๋ณด์ž.

<์˜ˆ์‹œ 1>

for x in range(0 , 4):
  print(x)
  if x == 2:
    print ('loop break')
    break
else:
  print ('loop end')
# ์ถœ๋ ฅ ๊ฒฐ๊ณผ
0
1
2
loop break

x==2๋ผ๋Š” ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋ฉด 'loop break'๋ฅผ ์ถœ๋ ฅ ํ›„, break๋กœ ๋ฐ˜๋ณต๋ฌธ์„ ๋น ์ ธ๋‚˜์˜จ๋‹ค.

<์˜ˆ์‹œ 2>

for x in range(0 , 4):
  print(x)
  pass
else:
  print ('loop end')
# ์ถœ๋ ฅ๊ฒฐ๊ณผ
0
1
2
3
loop end

break ์—†์ด ๋ชจ๋“  ๋ฐ˜๋ณต๋ฌธ์„ ์ˆ˜ํ–‰ ํ›„ else: ์ค„๋กœ ๋„˜์–ด๊ฐ€ 'loop end'๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

profile
ํ•˜์ด ์ด๊ฒƒ์€ ๋‚˜์˜ ๊นจ์ง€๊ณ  ๋ถ€์„œ์ง€๋Š” ๊ธฐ๋ก๋“ค์ž…๋‹ˆ๋‹ค
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€