์ƒˆ์†Œ์‹

Languages/Python

Python(while๋ฌธ, break, temp)

  • -
๋ฐ˜์‘ํ˜•

๋จผ์ € while๋ฌธ์— ๋Œ€ํ•œ ์˜ˆ์ œ ๋ช‡๊ฐ€์ง€๋ฅผ ์˜ฌ๋ฆฐ ํ›„ 

ํƒ€ ์–ธ์–ด๋“ค๊ณผ ๋‹ฌ๋ž๋˜ ์ ์„ ์ ์–ด๋ณด๊ฒ ๋‹ค.

 

์˜ˆ์ œ๋“ค์„ ๋ณด๋ฉฐ, ์‚ฌ์šฉ๋ฐฉ์‹์— ๋‹ค๋ฅธ ์ ์„ ์ฐพ์•„๊ฐ€๋ฉฐ ๊ณต๋ถ€ํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค.


 

 

์˜ˆ์‹œ 1) while๋ฌธ true and false

repeat = 1
while repeat == 1:
    print("๋งˆ์Œ์— ๋“œ๋Š” ๊ฒŒ์ž„์ด ์žˆ๋‚˜์š”?(์˜ˆ:1 /์•„๋‹ˆ์˜ค:0)")
    flag=int(input())

    if flag ==1:
        print("๋‹ค์šด๋กœ๋“œ ํ•˜๋Ÿฌ๊ฐ€๊ธฐ!")
        repeat=0
    else:
        print("๋‹ค์‹œ ํ•œ ๋ฒˆ! ๋‹ค๋ฅธ ๊ฒŒ์ž„ ์–ดํ”Œ์„ ๊ณจ๋ผ๋ณด์„ธ์š”")
        print("#####################################")
# ์ฐธ ๊ฑฐ์ง“์œผ๋กœ boolean ์œผ๋กœ ์ดํ•ดํ•ด๋„ ๋จ.

 

 

์˜ˆ์‹œ 2) ์ž๋ฆฌ๋ฐ”๊พธ๊ธฐ(c์–ธ์–ด์—์„  ์ž„์‹œ๋ณ€์ˆ˜ temp, swapํ•จ์ˆ˜๋ผ๊ณ ๋„ ํ•จ)

#๋ธŒ๋ ˆ์ดํฌ ๋ฌธ ์‹ค์Šต
print("์ฒซ ๋ฒˆ์งธ ์ˆ˜ ์ž…๋ ฅ :")
first = int(input())

print("๋‘ ๋ฒˆ์งธ ์ˆ˜ ์ž…๋ ฅ : ")
second =int(input())

if first > second:
    first,second = second,first
print("์ˆซ์ž ๋ฒ”์œ„ : %d~%d" %(first,second))

sum = 0 # ํ•ฉ๊ตฌํ•˜๊ธฐ
while first <=second:
    sum += first
    first += 1
print("๋ฒ”์œ„ ๋‚ด์— ํ•ฉ : ",sum)

# python์€ c์–ธ์–ด์™€ ๋‹ค๋ฅด๊ฒŒ ๊ฐ’์„๋ฐ”๊ฟ”์ค„๋•Œ temp (์ž„์‹œ๋ณ€์ˆ˜) ๊ฐ€ ๋”ฐ๋กœ ํ•„์š” ์—†๋‹ค.
# ์ฆ‰ a,b = b,a ์ด๋Ÿฐ์‹์œผ๋กœ๋งŒ ์จ์ฃผ๋ฉด ๋‘˜์˜ ๊ฐ’์ด ๋ฐ”๋€๋‹ค.

 

๊ฒฐ๊ณผ : 

ํฐ ์ˆ˜๊ฐ€ ์•ž์— ์˜ค๊ฒŒ ๋˜๋ฉด, ์ž๋ฆฌ๋ฅผ ๋ฐ”๊พธ์–ด ์ค€๋‹ค.

 

 

 

 

์˜ˆ์‹œ 3) while๋ฌธ ์˜ˆ์‹œ 

sum = 0

while True:
    print("์ฒซ๋ฒˆ์งธ ์ˆ˜ ์ž…๋ ฅ : ")
    num1 = int(input())
    print("๋‘๋ฒˆ์งธ ์ˆ˜ ์ž…๋ ฅ : ")
    num2 = int(input())

    if (num1 ==0) and (num2 ==0):
        break
    else:
        sum = sum + num1 + num2
        print("ํ•ฉ๊ณ„ : %d" %sum)

 

 

์˜ˆ์‹œ 4) 1~ ์ž…๋ ฅ ๊ฐ’ ์ค‘ 3์˜ ๋ฐฐ์ˆ˜๋งŒ ๋ชจ๋‘ ๋”ํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ

a = 0
sum = 0

num = int(input("์ˆ˜๋ฅผ ์ž…๋ ฅ : "))
while a <= num:
    a = a+1
    if(a%3)!=0:
        continue #๋ธŒ๋ ˆ์ดํฌ์˜ ๋ฐ˜๋Œ€.
    sum = sum +a
print("1~ %d๊นŒ์ง€์˜ 3์˜ ๋ฐฐ์ˆ˜ ํ•ฉ : %d" %(num,sum))

 

๊ฒฐ๊ณผ:


 

C์–ธ์–ด๋ž‘ ๋น„๊ตํ–ˆ์„ ๋•Œ ๊ฐœ์ธ์ ์œผ๋กœ ์ œ๊ฐ€ ๋Š๋‚€ ์ ์€

 

1. ์„ธ๋ฏธ์ฝœ๋ก ์„ ์ฐ์ง€ ์•Š๋Š”๋‹ค.

2. while, for, if๋ฌธ ๋“ฑ ๋’ค์— ์ฝœ๋ก ์„ ๋ถ™์—ฌ์ค€๋‹ค.

3. ๋ฌธ์žํ˜•์ด ๋งค์šฐ ๊นŒ๋‹ค๋กญ๋‹ค..?

4. ์ฝ”๋“œ๊ฐ€ ๋งค์šฐ์งง์•„์ง„๋‹ค.

 

์ •๋„ ์ธ ๊ฒƒ ๊ฐ™๋„ค์š”.. python์€ ๊ฐ์ข… ํˆด์„ ๋งŒ๋“ค๊ฑฐ๋‚˜, 

๋น ๋ฅด๊ณ  ๊ฐ„๋‹จํ•œ ํ”„๋กœ๊ทธ๋ž˜๋ฐ์„ ํ•  ๋•Œ ๋งค์šฐ ํŽธ๋ฆฌ ํ•˜๊ธฐ ๋•Œ๋ฌธ์—

๊พธ์ค€ํžˆ ์˜ˆ์‹œ๋ฅผ ์˜ฌ๋ ค๊ฐ€๋ฉฐ ๊ณต๋ถ€ ํ•˜๋„๋ก  ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค. 

 

 

๋ฐ˜์‘ํ˜•
Contents

ํฌ์ŠคํŒ… ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค

์ด ๊ธ€์ด ๋„์›€์ด ๋˜์—ˆ๋‹ค๋ฉด ๊ณต๊ฐ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.