๐Ÿ–ฅ๏ธ[Python] 5-2. ๋ฐ˜๋ณต๋ฌธ

thisk336ยท2023๋…„ 5์›” 15์ผ
0

Python

๋ชฉ๋ก ๋ณด๊ธฐ
7/17
post-thumbnail

for statement

  • while๋ฌธ์€ ์กฐ๊ฑด์ด ๋งŒ์กฑํ•˜๋Š” ๋™์•ˆ ๋ฐ˜๋ณต์„ ์ˆ˜ํ–‰ํ–ˆ์ง€๋งŒ, for๋ฌธ์€ ์ง€์ • ํšŸ์ˆ˜๋™์•ˆ ๋ฐ˜๋ณต์„ ์ˆ˜ํ–‰ํ•œ๋‹ค.

    ์—ฌ๊ธฐ์„œ ์ง€์ •๋œ ํšŸ์ˆ˜๋ผ๋Š” ๊ฒƒ์€ ๋ฐ˜๋ณต ๋Œ€์ƒ์˜ ํฌ๊ธฐ๊ฐ€ ๋œ๋‹ค.

  • ๋ณดํ†ต iteratable object(๋ฐ˜๋ณต ๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด)๋ฅผ ๋Œ€์ƒ์œผ๋กœ ์ˆ˜ํ–‰๋˜๋ฉฐ, ์—ฐ์†ํ˜• ๋ฐ์ดํ„ฐ ํƒ€์ž… ๋ณ€์ˆ˜๋“ค์ด ์—ฌ๊ธฐ์— ํ•ด๋‹น๋œ๋‹ค.

    List, Tuple, string, ...

  • for ๋ณ€์ˆ˜ in ๋ฆฌ์ŠคํŠธ(ํŠœํ”Œ, ๋ฌธ์ž์—ด, iterator):
    (statement1)
    (statement2)
    (statement3)
  • ๋ฆฌ์ŠคํŠธ(๋‚˜ ๋ฐ˜๋ณต๊ฐ€๋Šฅํ•œ ๋ณ€์ˆ˜๋“ค)์˜ ๋ชจ๋“  ์›์†Œ๋ฅผ (์ž๋™์œผ๋กœ ๋๊นŒ์ง€) ๋ฐ˜๋ณตํ•œ๋‹ค.
L = [1,2,3]
for i in L :
    print(i)
    
coffees = ['์•„๋ฉ”๋ฆฌ์นด๋…ธ', '์นดํŽ˜๋ผ๋–ผ', '์นดํŽ˜๋ชจ์นด', '๋ฐ”๋‹๋ผ๋ผ๋–ผ', 'ํ•ธ๋“œ๋“œ๋ฆฝ', '์ฝœ๋“œ๋ธŒ๋ฃจ']
for coffee in coffees :
    print(coffee)

for๋ฌธ์˜ ๋‹จ์ง range() ํ•จ์ˆ˜

  • for๋ฌธ์€ ํŠน์ • ํšŸ์ˆ˜๋™์•ˆ ๋ฐ˜๋ณต์„ ํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ํšŸ์ˆ˜๋ฅผ ์ž๋™์œผ๋กœ ๋งŒ๋“ค์–ด์ฃผ๋Š” ๊ธฐ๋Šฅ์ด ์žˆ์œผ๋ฉด ์ข‹๋‹ค.

  • ํŒŒ์ด์ฌ์—์„œ ๊ธฐ๋ณธ์ ์œผ๋กœ ์ œ๊ณตํ•˜๋Š” range ํ•จ์ˆ˜๋Š” ํŠน์ • ์ˆซ์ž ๋ฒ”์œ„๋‚ด์˜ ๊ฐ’๋“ค์„ ์ž๋™์œผ๋กœ ์ƒ์„ฑํ•ด์ฃผ๋Š” ํ•จ์ˆ˜์ด๋‹ค.

e.g. range(1, 5)๋Š” 1, 2, 3, 4๋ฅผ ์ฐจ๋ก€๋Œ€๋กœ ์ƒ์„ฑํ•ด์ค€๋‹ค. (5๋Š” ๋ฒ”์œ„์—์„œ ์ œ์™ธ๋œ๋‹ค. ์ฆ‰, ๋งˆ์ง€๋ง‰ ์ˆซ์ž๋Š” ์ œ์™ธ๋œ๋‹ค. 1 <= x < 5)

# range ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•œ ๊ตฌ๊ตฌ๋‹จ
for i in range(1,10) :
    print(f"{i}๋‹จ")
    for j in range(1,10) :
        print(f"{i} X {j} = {i*j}")
    print(" ")

6๊ฐœ์˜ ์ปคํ”ผ ์Œ๋ฃŒ์™€ ์Œ๋ฃŒ์˜ ๊ฐ€๊ฒฉ์ด ๋‹ด๊ธด ๋ฆฌ์ŠคํŠธ๊ฐ€ ์žˆ๋‹ค. ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๋ˆ์ด 5,000์›์ผ ๋•Œ ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ์Œ๋ฃŒ๋ฅผ ์ฐพ์•„๋ณด์ž

# index๋ฅผ ํ™œ์šฉํ•œ ๋ฐฉ๋ฒ•
for i in range(6) :
    if prices[i] <= 5000 :
        print(coffees[i])

# enumerete ํ•จ์ˆ˜๋ฅผ ํ™œ์šฉํ•œ ๋ฐฉ๋ฒ•
for i, price in enumerate(prices) :
    if price <= 5000 :
        print(coffees[i])
        
# zip ํ•จ์ˆ˜๋ฅผ ํ™œ์šฉํ•œ ๋ฐฉ๋ฒ•
for coffee, price in zip(coffees, prices) :
    if price <= 5000:
        print(coffee)

RE : 6๊ฐœ์˜ ์ปคํ”ผ ์Œ๋ฃŒ์™€ ์Œ๋ฃŒ์˜ ๊ฐ€๊ฒฉ์ด ๋‹ด๊ธด ๋ฆฌ์ŠคํŠธ๊ฐ€ ์žˆ๋‹ค. ์˜ค๋Š˜์€ ํ• ์ธ ํ–‰์‚ฌ๋ฅผ ํ•˜์—ฌ ๋ชจ๋“  ์Œ๋ฃŒ๊ฐ€ 500์› ํ• ์ธ ๋˜์—ˆ์„ ๋•Œ, ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๋ˆ์ด 5,000์›์ผ ๋•Œ ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ์Œ๋ฃŒ๋ฅผ ์ฐพ์•„๋ณด์ž

coffees = ['์•„๋ฉ”๋ฆฌ์นด๋…ธ', '์นดํŽ˜๋ผ๋–ผ', '์นดํŽ˜๋ชจ์นด', '๋ฐ”๋‹๋ผ๋ผ๋–ผ', 'ํ•ธ๋“œ๋“œ๋ฆฝ', '์ฝœ๋“œ๋ธŒ๋ฃจ']
prices = [4100, 4600, 4600, 5100, 6000, 5000]

# ์ฒซ๋ฒˆ์งธ ๋ฐฉ๋ฒ•
for i, price in enumerate(prices) :
    if price <= 5500 :
        print(coffees[i])
        
# ๋‘๋ฒˆ์งธ ๋ฐฉ๋ฒ•
for i, price in enumerate(prices) :
    if price - 500 <= 5000 :
        print(coffees[i])

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