KR_While - somaz94/python-study GitHub Wiki
while๋ฌธ์ ์กฐ๊ฑด์ด ์ฐธ์ธ ๋์ ์ฝ๋ ๋ธ๋ก์ ๋ฐ๋ณต์ ์ผ๋ก ์คํํ๋ ๋ฐ๋ณต๋ฌธ์ด๋ค. ์กฐ๊ฑด์ด ๊ฑฐ์ง์ด ๋ ๋๊น์ง ๊ณ์ํด์ ์คํ๋๋ค.
# ๊ธฐ๋ณธ while๋ฌธ ๊ตฌ์กฐ
while ์กฐ๊ฑด:
์ํํ _๋ฌธ์ฅ1
์ํํ _๋ฌธ์ฅ2
...
# ์์ : 1๋ถํฐ 5๊น์ง ์ถ๋ ฅ
number = 1
while number <= 5:
print(number)
number += 1
โ ์ฃผ์์ฌํญ:
- ๋ฌดํ ๋ฃจํ ์ฃผ์
- ์กฐ๊ฑด๋ฌธ ํ์
- ๋ค์ฌ์ฐ๊ธฐ ํ์
# break: ๋ฐ๋ณต๋ฌธ ์ข
๋ฃ
coffee = 10
while True:
if coffee == 0:
print("์ปคํผ๊ฐ ๋ชจ๋ ์์ง๋์์ต๋๋ค.")
break
print(f"๋จ์ ์ปคํผ: {coffee}์")
coffee -= 1
# continue: ํ์ฌ ๋ฐ๋ณต์ ๊ฑด๋๋ฐ๊ณ ๋ค์ ๋ฐ๋ณต์ผ๋ก
number = 0
while number < 10:
number += 1
if number % 2 == 0:
continue # ์ง์๋ฉด ์ถ๋ ฅํ์ง ์์
print(number) # ํ์๋ง ์ถ๋ ฅ
โ ์ ์ด๋ฌธ:
-
break
: ๋ฐ๋ณต๋ฌธ์ ์์ ํ ์ข ๋ฃ -
continue
: ํ์ฌ ๋ฐ๋ณต์ ๊ฑด๋๋ฐ๊ณ ๋ค์ ๋ฐ๋ณต์ผ๋ก - ์กฐ๊ฑด๋ฌธ๊ณผ ํจ๊ป ์์ฃผ ์ฌ์ฉ
# ๋ฌดํ ๋ฃจํ ๊ธฐ๋ณธ ๊ตฌ์กฐ
while True:
user_input = input("์ข
๋ฃํ๋ ค๋ฉด 'q'๋ฅผ ์
๋ ฅํ์ธ์: ")
if user_input == 'q':
break
print("์
๋ ฅ๊ฐ:", user_input)
# ์ค์ ์์ฉ ์์
def calculator():
while True:
command = input("๊ณ์ฐํ ์์ ์
๋ ฅํ์ธ์ (์ข
๋ฃ: q): ")
if command == 'q':
break
try:
result = eval(command)
print(f"๊ฒฐ๊ณผ: {result}")
except:
print("์ฌ๋ฐ๋ฅธ ์์์ ์
๋ ฅํ์ธ์")
โ ๋ฌดํ ๋ฃจํ ํน์ง:
-
while True:
ํํ๋ก ์์ฑ - ๋ฐ๋์ ์ข ๋ฃ ์กฐ๊ฑด ํ์
- ์ค์๋ก ๋ง๋ค๋ฉด ํ๋ก๊ทธ๋จ ๊ฐ์ ์ข ๋ฃ ํ์
# ์ฌ์ฉ์ ์
๋ ฅ ์ฒ๋ฆฌ
def menu_system():
while True:
print("\n1. ํ์ผ ์ด๊ธฐ")
print("2. ํ์ผ ์ ์ฅ")
print("3. ์ข
๋ฃ")
choice = input("์ ํํ์ธ์: ")
if choice == '1':
print("ํ์ผ์ ์ฝ๋๋ค.")
elif choice == '2':
print("ํ์ผ์ ์ ์ฅํฉ๋๋ค.")
elif choice == '3':
print("ํ๋ก๊ทธ๋จ์ ์ข
๋ฃํฉ๋๋ค.")
break
else:
print("์๋ชป๋ ์ ํ์
๋๋ค.")
# ์กฐ๊ฑด๋ถ ๋ฐ๋ณต
def countdown(n):
while n > 0:
print(n)
n -= 1
print("๋ฐ์ฌ!")
โ ํ์ฉ Tip:
- ์ฌ์ฉ์ ์ ๋ ฅ ์ฒ๋ฆฌ
- ๊ฒ์ ๋ฃจํ ๊ตฌํ
- ๋ฐ์ดํฐ ์ฒ๋ฆฌ
- ํ์ผ ์ฒ๋ฆฌ
- ๋คํธ์ํฌ ํต์
while๋ฌธ์์๋ for๋ฌธ๊ณผ ๋ง์ฐฌ๊ฐ์ง๋ก else ๊ตฌ๋ฌธ์ ์ฌ์ฉํ ์ ์๋ค. while ์กฐ๊ฑด์ด ๊ฑฐ์ง์ด ๋์ด ๋ฃจํ๊ฐ ์ ์์ ์ผ๋ก ์ข ๋ฃ๋ ๋ else ๋ธ๋ก์ด ์คํ๋๋ค. break๋ก ๋ฃจํ๊ฐ ์ข ๋ฃ๋๋ฉด else ๋ธ๋ก์ ์คํ๋์ง ์๋๋ค.
# ๊ธฐ๋ณธ ๊ตฌ์กฐ
while ์กฐ๊ฑด:
# ์กฐ๊ฑด์ด ์ฐธ์ธ ๋์ ์คํ
์ํํ _๋ฌธ์ฅ
else:
# ์กฐ๊ฑด์ด ๊ฑฐ์ง์ด ๋์ด ๋ฃจํ๊ฐ ์ข
๋ฃ๋๋ฉด ์คํ
์ข
๋ฃ_ํ_์ํํ _๋ฌธ์ฅ
# ์์ ์ฐพ๊ธฐ ์์
def is_prime(n):
if n <= 1:
return False
i = 2
while i * i <= n:
if n % i == 0:
print(f"{n}์ {i}๋ก ๋๋์ด๋จ์ด์ง๋๋ค.")
break
i += 1
else:
print(f"{n}์ ์์์
๋๋ค.")
return True
return False
# ์ฌ์ฉ ์์
is_prime(17) # ์ถ๋ ฅ: 17์ ์์์
๋๋ค.
is_prime(25) # ์ถ๋ ฅ: 25์ 5๋ก ๋๋์ด๋จ์ด์ง๋๋ค.
โ while-else ํน์ง:
- ๋ฃจํ๊ฐ ์ ์์ ์ผ๋ก ์ข ๋ฃ๋ ๋๋ง else ๋ธ๋ก ์คํ
- break๋ก ์ค๋จ๋๋ฉด else ๋ธ๋ก ์คํ๋์ง ์์
- ๊ฒ์, ์ ํจ์ฑ ๊ฒ์ฌ ๋ฑ์ ์ ์ฉํ๊ฒ ์ฌ์ฉ
- ์ฝ๋์ ์๋๋ฅผ ๋ช ํํ๊ฒ ํํ ๊ฐ๋ฅ
์ค์ฒฉ๋ ๋ฐ๋ณต๋ฌธ์์์ ์ ์ด ํ๋ฆ๊ณผ best practice์ ๋ํด ์์๋ณธ๋ค.
# ๊ธฐ๋ณธ ์ค์ฒฉ while๋ฌธ
i = 1
while i <= 5:
j = 1
while j <= i:
print("*", end="")
j += 1
print() # ์ค๋ฐ๊ฟ
i += 1
# ์ค์ฒฉ ๋ฃจํ์์ ํน์ ๋ฃจํ๋ง ์ข
๋ฃํ๊ธฐ
i = 1
while i <= 5:
j = 1
while j <= 5:
print(f"({i}, {j})", end=" ")
if j == 3:
break # ๋ด๋ถ ๋ฃจํ๋ง ์ข
๋ฃ
j += 1
print()
i += 1
# ์ค์ฒฉ ๋ฃจํ์์ ๋ชจ๋ ๋ฃจํ ์ข
๋ฃํ๊ธฐ
found = False
i = 1
while i <= 5 and not found:
j = 1
while j <= 5:
if i * j > 10:
print(f"์ฒซ ๋ฒ์งธ 10๋ณด๋ค ํฐ ๊ณฑ: {i} * {j} = {i*j}")
found = True
break # ๋ด๋ถ ๋ฃจํ ์ข
๋ฃ
j += 1
i += 1
โ ์ค์ฒฉ ๋ฃจํ ์ ์ด ๊ธฐ๋ฒ:
- ํ๋๊ทธ ๋ณ์ ํ์ฉ
- ํจ์๋ก ๋ถ๋ฆฌํ์ฌ return ์ฌ์ฉ
- ๊ฐ ๋ฃจํ์ ์ญํ ๋ช ํํ ๊ตฌ๋ถ
- ๊ฐ๋ฅํ๋ฉด ๊น์ ์ค์ฒฉ ํผํ๊ธฐ
- ๋ฐ๋ณต๋ฌธ ์ถ์ถ ๋ฆฌํฉํ ๋ง ๊ณ ๋ ค
while๋ฌธ์ ์ฌ์ฉํ ๋ ์ฑ๋ฅ์ ํฅ์์ํค๋ ๋ฐฉ๋ฒ์ด๋ค.
import time
# ์ต์ ํ ์
def compute_factorial_unoptimized(n):
result = 1
while n > 0:
result *= n
n -= 1
return result
# ์ต์ ํ 1: ์กฐ๊ฑด ๊ฒ์ฌ ์ต์ํ
def compute_factorial_optimized1(n):
result = 1
while n > 1: # n > 0 ๋์ n > 1 ์ฌ์ฉ (๋ถํ์ํ ๊ณฑ์
ํํผ)
result *= n
n -= 1
return result
# ์ต์ ํ 2: ์ง์ญ ๋ณ์ ํ์ฉ
def compute_factorial_optimized2(n):
result = 1
i = 2 # 1๋ถํฐ ์์ํ์ง ์๊ณ 2๋ถํฐ ์์
while i <= n:
result *= i
i += 1
return result
# ์ต์ ํ 3: ๊ณ์ฐ ์ค์ด๊ธฐ
def compute_factorial_optimized3(n):
if n <= 1:
return 1
result = 1
i = n
while i > 1:
result *= i
i -= 1
return result
# ์ต์ ํ ์ : ๋ฃจํ ๋ด๋ถ์์ ์กฐ๊ฑด ๋งค๋ฒ ๊ณ์ฐ
def find_in_sorted_list(sorted_list, target):
i = 0
while i < len(sorted_list): # ๋งค๋ฒ len() ํธ์ถ
if sorted_list[i] == target:
return i
elif sorted_list[i] > target: # ์ ๋ ฌ๋ ๋ฆฌ์คํธ์์ ํ๊ฒ๋ณด๋ค ํฐ ๊ฐ์ ๋ง๋๋ฉด ์ข
๋ฃ
break
i += 1
return -1
# ์ต์ ํ ํ: ์กฐ๊ฑด์ ๋ฏธ๋ฆฌ ๊ณ์ฐ
def find_in_sorted_list_optimized(sorted_list, target):
i = 0
length = len(sorted_list) # ํ ๋ฒ๋ง ๊ณ์ฐ
while i < length:
value = sorted_list[i] # ๋ฐ๋ณต์ ์ธ๋ฑ์ฑ ๋ฐฉ์ง
if value == target:
return i
elif value > target:
break
i += 1
return -1
โ ์ฑ๋ฅ ์ต์ ํ ์์น:
- ๋ฐ๋ณต์ ์ธ ํจ์ ํธ์ถ ํผํ๊ธฐ
- ๋ฃจํ ๋ด๋ถ ์ฐ์ฐ ์ต์ํ
- ๋ถํ์ํ ์กฐ๊ฑด ๊ฒ์ฌ ์ ๊ฑฐ
- ์ง์ญ ๋ณ์ ํ์ฉ์ผ๋ก ์ฐธ์กฐ ์๋ ํฅ์
- ์ ์ ํ ์ข ๋ฃ ์กฐ๊ฑด ์ค์
์ค์ ํ๋ก๊ทธ๋๋ฐ์์ ์์ฃผ ์ฌ์ฉ๋๋ ๊ณ ๊ธ ํจํด์ด๋ค.
import time
def retry_operation(max_attempts=3, timeout=10):
start_time = time.time()
attempts = 0
while attempts < max_attempts and (time.time() - start_time) < timeout:
attempts += 1
try:
# ์คํํ ์์
print(f"์๋ {attempts}...")
if attempts == 2: # ์ฑ๊ณต ์๋ฎฌ๋ ์ด์
print("์์
์ฑ๊ณต!")
return True
except Exception as e:
print(f"์ค๋ฅ ๋ฐ์: {e}")
time.sleep(1) # ์ฌ์๋ ์ ๋๊ธฐ
print("์ต๋ ์๋ ํ์ ์ด๊ณผ ๋๋ ์๊ฐ ์ด๊ณผ")
return False
# ์ฌ์ฉ ์์
retry_operation()
import queue
import threading
import time
import random
# ๊ณต์ ํ
buffer = queue.Queue(maxsize=10)
RUNNING = True
def producer():
"""๋ฐ์ดํฐ๋ฅผ ์์ฑํ์ฌ ๋ฒํผ์ ์ถ๊ฐ"""
count = 0
while RUNNING:
if not buffer.full():
item = f"์์ดํ
-{count}"
buffer.put(item)
print(f"์์ฐ: {item}")
count += 1
time.sleep(random.uniform(0.1, 0.5))
def consumer():
"""๋ฒํผ์์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ ์ฒ๋ฆฌ"""
while RUNNING:
if not buffer.empty():
item = buffer.get()
print(f"์๋น: {item}")
buffer.task_done()
time.sleep(random.uniform(0.2, 0.7))
# ์ค๋ ๋ ์์
producer_thread = threading.Thread(target=producer)
consumer_thread = threading.Thread(target=consumer)
producer_thread.start()
consumer_thread.start()
# 10์ด ๋์ ์คํ ํ ์ข
๋ฃ
time.sleep(10)
RUNNING = False
producer_thread.join()
consumer_thread.join()
def wait_for_resource(resource_check_fn, timeout=30, check_interval=1):
"""๋ฆฌ์์ค๊ฐ ์ค๋น๋ ๋๊น์ง ์ฃผ๊ธฐ์ ์ผ๋ก ํ์ธ"""
start_time = time.time()
while (time.time() - start_time) < timeout:
if resource_check_fn():
print("๋ฆฌ์์ค ์ค๋น ์๋ฃ!")
return True
print("๋ฆฌ์์ค ์ค๋น ์ค...")
time.sleep(check_interval)
print("๋ฆฌ์์ค ์ค๋น ์๊ฐ ์ด๊ณผ")
return False
# ์ฌ์ฉ ์์
def is_database_ready():
# ์ค์ ๋ก๋ ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ฐ๊ฒฐ ํ์ธ
import random
return random.random() > 0.7
wait_for_resource(is_database_ready)
โ ๊ณ ๊ธ ํจํด ์ฅ์ :
- ์ฌ์๋ ๋ก์ง ํ์คํ
- ๋์์ฑ ์ฒ๋ฆฌ ํจํด ์ ๊ณต
- ํ์์์ ๊ด๋ฆฌ ์ฉ์ด
- ๋น๋๊ธฐ ์์ ์กฐ์จ
- ์๋ฌ ์ํฉ ์ฐ์ํ ์ฒ๋ฆฌ
while๋ฌธ๊ณผ ์ ๋๋ ์ดํฐ๋ฅผ ํจ๊ป ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ์ด๋ค.
# ๊ธฐ๋ณธ ์ ๋๋ ์ดํฐ
def fibonacci_generator(limit):
a, b = 0, 1
count = 0
while count < limit:
yield a
a, b = b, a + b
count += 1
# ์ฌ์ฉ ์์
for num in fibonacci_generator(10):
print(num) # 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
# ๋ฌดํ ์ ๋๋ ์ดํฐ
def infinite_counter(start=0, step=1):
"""๋ฌดํํ ๊ฐ์ ์์ฑํ๋ ์ ๋๋ ์ดํฐ"""
n = start
while True:
yield n
n += step
# ํ์ํ ๋งํผ๋ง ์๋น
for i, num in enumerate(infinite_counter(10, 5)):
print(num)
if i >= 5: # ์ฒ์ 6๊ฐ ๊ฐ๋ง ๊ฐ์ ธ์ด
break
# ์ ๋๋ ์ดํฐ ํํ์
def evens_under(n):
"""n ๋ฏธ๋ง์ ์ง์๋ฅผ ์์ฑํ๋ ์ ๋๋ ์ดํฐ ํํ์"""
return (i for i in range(n) if i % 2 == 0)
# ์ง์ฐ ํ๊ฐ(Lazy Evaluation) ํ์ฉ
def search_in_large_file(file_path, search_term):
"""๋์ฉ๋ ํ์ผ์์ ํน์ ๋จ์ด๊ฐ ํฌํจ๋ ์ค ์ฐพ๊ธฐ"""
with open(file_path, 'r') as file:
line_number = 0
while True:
line = file.readline()
if not line: # ํ์ผ ๋
break
line_number += 1
if search_term in line:
yield (line_number, line.strip())
โ ์ ๋๋ ์ดํฐ ์ฅ์ :
- ๋ฉ๋ชจ๋ฆฌ ํจ์จ์ฑ (ํ์ํ ๋๋ง ๊ฐ ์์ฑ)
- ๋์ฉ๋ ๋ฐ์ดํฐ ์ฒ๋ฆฌ ๊ฐ๋ฅ
- ๋ฌดํ ์ํ์ค ์ฒ๋ฆฌ ๊ฐ๋ฅ
- ์ง์ฐ ํ๊ฐ๋ก ์ฑ๋ฅ ํฅ์
- I/O ๋ฐ์ด๋ ์์ ์ ํจ์จ ํฅ์
๋น๋๊ธฐ ํ๋ก๊ทธ๋๋ฐ์์ while๋ฌธ์ ํ์ฉํ๋ ๋ฐฉ๋ฒ์ด๋ค.
import asyncio
# ๋น๋๊ธฐ while ๋ฃจํ
async def async_counter(limit):
count = 0
while count < limit:
print(f"์นด์ดํธ: {count}")
await asyncio.sleep(0.5) # ๋น์ฐจ๋จ ๋๊ธฐ
count += 1
return count
# ๋น๋๊ธฐ ์ด๋ฒคํธ ์ฒ๋ฆฌ
async def event_processor(queue, timeout=None):
start_time = asyncio.get_event_loop().time()
while timeout is None or (asyncio.get_event_loop().time() - start_time) < timeout:
try:
# 0.1์ด ๋์ ํ์์ ํญ๋ชฉ ๋๊ธฐ
event = await asyncio.wait_for(queue.get(), 0.1)
print(f"์ด๋ฒคํธ ์ฒ๋ฆฌ: {event}")
queue.task_done()
except asyncio.TimeoutError:
print("์ด๋ฒคํธ ๋๊ธฐ ์ค...")
# ํ๊ฐ ๋น์ด์์ด๋ ๋ฃจํ ๊ณ์ ์คํ
continue
# ๋น๋๊ธฐ ์์
๋์ ์คํ
async def concurrent_tasks():
# ์ด๋ฒคํธ ํ ์์ฑ
event_queue = asyncio.Queue()
# ์ด๋ฒคํธ ์์ฑ์ ํจ์
async def event_generator():
for i in range(10):
event = f"์ด๋ฒคํธ-{i}"
await event_queue.put(event)
print(f"์ด๋ฒคํธ ์์ฑ: {event}")
await asyncio.sleep(0.7)
# ๋ ์์
๋์ ์คํ
await asyncio.gather(
event_generator(),
event_processor(event_queue, timeout=10)
)
# ๋น๋๊ธฐ ํ์์์ ํจํด
async def with_timeout(coroutine, timeout=5.0):
try:
return await asyncio.wait_for(coroutine, timeout)
except asyncio.TimeoutError:
print("์์
์๊ฐ ์ด๊ณผ")
return None
# ์ฌ์ฉ ์์
async def main():
# ์นด์ดํฐ ์คํ
await with_timeout(async_counter(10), 3.0)
# ๋์ ์์
์คํ
await concurrent_tasks()
# ๋น๋๊ธฐ ๋ฉ์ธ ํจ์ ์คํ
asyncio.run(main())
โ ๋น๋๊ธฐ while๋ฌธ ํน์ง:
-
asyncio.sleep()
๋ก ๋น์ฐจ๋จ ๋๊ธฐ - ๋ค๋ฅธ ์ฝ๋ฃจํด์ ์คํ์ ํ์ฉ
- ๋น๋๊ธฐ ํ๋ฅผ ํ์ฉํ ํต์
- ํ์์์ ํจํด ์ง์
- ์ด๋ฒคํธ ๊ธฐ๋ฐ ํ๋ก๊ทธ๋๋ฐ ๊ฐ๋ฅ
while๋ฌธ์ ํ์ฉํ ์ํ ๊ธฐ๊ณ(State Machine) ๊ตฌํ ๋ฐฉ๋ฒ์ด๋ค.
class StateMachine:
def __init__(self, initial_state):
self.state = initial_state
self.handlers = {}
self.end_states = []
def add_state(self, name, handler, end_state=False):
"""์ํ ์ถ๊ฐ"""
self.handlers[name] = handler
if end_state:
self.end_states.append(name)
def run(self, cargo):
"""์ํ ๊ธฐ๊ณ ์คํ"""
while self.state not in self.end_states:
# ํ์ฌ ์ํ์ ๋ํ ํธ๋ค๋ฌ ๊ฐ์ ธ์ค๊ธฐ
handler = self.handlers[self.state]
# ํธ๋ค๋ฌ ์คํ ๋ฐ ๋ค์ ์ํ์ ํ๋ฌผ ๋ฐ๊ธฐ
self.state, cargo = handler(cargo)
return cargo
# ์์ : ํ
์คํธ ์ฒ๋ฆฌ ์ํ ๊ธฐ๊ณ
def start_state(text):
"""์์ ์ํ: ํ
์คํธ ์ค๋น"""
words = text.split()
return 'process_words', words
def process_words(words):
"""๋จ์ด ์ฒ๋ฆฌ ์ํ"""
if not words:
return 'end', []
processed_words = [word.strip('.,!?').lower() for word in words]
return 'count_length', processed_words
def count_length(words):
"""๊ธธ์ด ๊ณ์ฐ ์ํ"""
word_lengths = [(word, len(word)) for word in words]
return 'end', word_lengths
# ์ํ ๊ธฐ๊ณ ์์ฑ ๋ฐ ์คํ
def process_text(text):
sm = StateMachine('start')
sm.add_state('start', start_state)
sm.add_state('process_words', process_words)
sm.add_state('count_length', count_length)
sm.add_state('end', None, end_state=True)
result = sm.run(text)
return result
# ์ฌ์ฉ ์์
text = "Python์ ๊ฐ๊ฒฐํ๊ณ ์ฝ๊ธฐ ์ฌ์ด ํ๋ก๊ทธ๋๋ฐ ์ธ์ด์
๋๋ค!"
word_lengths = process_text(text)
for word, length in word_lengths:
print(f"'{word}': {length}์")
โ ์ํ ๊ธฐ๊ณ ์ฅ์ :
- ๋ณต์กํ ํ๋ฆ์ ๋ช ํํ ํํ
- ์ํ ์ ํ ๋ก์ง ๋ถ๋ฆฌ
- ์ฝ๋ ์ ์ง๋ณด์์ฑ ํฅ์
- ํ์ฅ์ฑ์ด ๋์ ๊ตฌ์กฐ
- ํ ์คํธ ์ฉ์ด์ฑ
while๋ฌธ ์ฌ์ฉ ์ ํํ ๋ฌธ์ ํด๊ฒฐ ๋ฐฉ๋ฒ๊ณผ ๋๋ฒ๊น ํ ํฌ๋์ด๋ค.
- ๋ฌดํ ๋ฃจํ
# ๋ฌธ์ : ์ข
๋ฃ ์กฐ๊ฑด์ด ์ถฉ์กฑ๋์ง ์์
i = 10
while i > 0:
print(i)
# i -= 1 # ์ฃผ์ ํด์ ๋ก ํด๊ฒฐ
# ํด๊ฒฐ: ํ์์์ ํจํด ์ ์ฉ
def with_timeout(func, args=(), timeout=5):
import threading
import time
result = [None]
exception = [None]
def worker():
try:
result[0] = func(*args)
except Exception as e:
exception[0] = e
thread = threading.Thread(target=worker)
thread.daemon = True
thread.start()
thread.join(timeout)
if thread.is_alive():
raise TimeoutError(f"ํจ์ ์คํ์ด {timeout}์ด๋ฅผ ์ด๊ณผํ์ต๋๋ค.")
if exception[0]:
raise exception[0]
return result[0]
- ์๋ชป๋ ์กฐ๊ฑด
# ๋ฌธ์ : ์กฐ๊ฑด ํ๊ฐ ์ค๋ฅ
data = [1, 2, 3]
i = 0
while i < len(data):
print(data[i])
data.append(i) # ๋งค ๋ฐ๋ณต๋ง๋ค ๋ฆฌ์คํธ ํฌ๊ธฐ๊ฐ ์ฆ๊ฐํด ๋ฌดํ ๋ฃจํ ๋ฐ์
i += 1
# ํด๊ฒฐ: ๋ณ๋ ๋ณ์์ ๊ธธ์ด ์ ์ฅ
data = [1, 2, 3]
i = 0
length = len(data) # ์ฒ์ ๊ธธ์ด๋ง ์ฌ์ฉ
while i < length:
print(data[i])
data.append(i) # ๋ฃจํ ์กฐ๊ฑด์ ์ํฅ ์์
i += 1
- ์คํ๋ฐ์ด์(Off-by-one) ์ค๋ฅ
# ๋ฌธ์ : ํ ๋ฒ ๋ ๋ฐ๋ณตํ๊ฑฐ๋ ํ ๋ฒ ๋ ๋ฐ๋ณต
arr = [10, 20, 30, 40, 50]
i = 0
while i <= len(arr): # ์๋ชป๋ ์กฐ๊ฑด (<=)
# ์ธ๋ฑ์ค ์ค๋ฅ ๋ฐ์
print(arr[i])
i += 1
# ํด๊ฒฐ: ์ ํํ ์กฐ๊ฑด ์ฌ์ฉ
i = 0
while i < len(arr): # ์ฌ๋ฐ๋ฅธ ์กฐ๊ฑด (<)
print(arr[i])
i += 1
# ๋ก๊น
์ถ๊ฐ
import logging
logging.basicConfig(level=logging.DEBUG)
def process_with_logging(data):
i = 0
while i < len(data):
logging.debug(f"์ธ๋ฑ์ค: {i}, ๊ฐ: {data[i]}")
# ์ฒ๋ฆฌ ๋ก์ง
i += 1
# ์ํ ์ค๋
์ท
def process_with_snapshot(data, max_iterations=1000):
i = 0
iterations = 0
while i < len(data) and iterations < max_iterations:
# ์ฃผ๊ธฐ์ ์ผ๋ก ์ํ ์ถ๋ ฅ
if iterations % 100 == 0:
print(f"์งํ ์ํฉ: {i}/{len(data)}")
# ์ฒ๋ฆฌ ๋ก์ง
i += 1
iterations += 1
if iterations >= max_iterations:
print("์ต๋ ๋ฐ๋ณต ํ์ ์ด๊ณผ")
โ ๋๋ฒ๊น ํ:
- ์ค๊ฐ ๊ฐ ์ถ๋ ฅ
- ๋ฐ๋ณต ํ์ ์ ํ
- ์ฌํ ๊ฐ๋ฅํ ํ ์คํธ ์ผ์ด์ค ์์ฑ
- ๋ก๊น ๋ผ์ด๋ธ๋ฌ๋ฆฌ ํ์ฉ
- ๊ฐ์ ๊ฒ์ฆํ๊ธฐ
- ๋ ์์ ๋ฌธ์ ๋ก ๋๋๊ธฐ