KR_If - somaz94/python-study GitHub Wiki
if๋ฌธ์ ํน์ ์กฐ๊ฑด์ ๋ฐ๋ผ ๋ค๋ฅธ ์ฝ๋๋ฅผ ์คํํ๊ฒ ํ๋ ์ ์ด๋ฌธ์ด๋ค. ์กฐ๊ฑด์ด ์ฐธ(True)์ผ ๋์ ๊ฑฐ์ง(False)์ผ ๋ ์๋ก ๋ค๋ฅธ ์ฝ๋๋ฅผ ์คํํ ์ ์๋ค.
# ๊ธฐ๋ณธ if๋ฌธ ๊ตฌ์กฐ
if ์กฐ๊ฑด:
# ์กฐ๊ฑด์ด ์ฐธ์ผ ๋ ์คํํ ์ฝ๋
์ํํ _๋ฌธ์ฅ1
์ํํ _๋ฌธ์ฅ2
else:
# ์กฐ๊ฑด์ด ๊ฑฐ์ง์ผ ๋ ์คํํ ์ฝ๋
์ํํ _๋ฌธ์ฅA
์ํํ _๋ฌธ์ฅB
โ ์ฃผ์์ฌํญ:
- ์ฝ๋ก (:) ํ์
- ๋ค์ฌ์ฐ๊ธฐ ํ์ (๋ณดํต 4์นธ ๊ณต๋ฐฑ ์ฌ์ฉ)
- ๋ค์ฌ์ฐ๊ธฐ๋ ์ผ๊ด์ฑ ์๊ฒ ์ฌ์ฉ
# ๋น๊ต ์ฐ์ฐ์ ์ฌ์ฉ
x = 10
if x > 0:
print("์์์
๋๋ค")
# ๋
ผ๋ฆฌ ์ฐ์ฐ์ ์ฌ์ฉ
age = 25
money = 5000
if age >= 20 and money >= 10000:
print("์
์ฅ ๊ฐ๋ฅ")
# in, not in ์ฐ์ฐ์
fruits = ['apple', 'banana', 'orange']
if 'apple' in fruits:
print("์ฌ๊ณผ๊ฐ ์์ต๋๋ค")
โ ์ฃผ์ ์ฐ์ฐ์:
- ๋น๊ต:
<
,>
,==
,!=
,>=
,<=
- ๋
ผ๋ฆฌ:
and
,or
,not
- ๋ฉค๋ฒ์ญ:
in
,not in
# ์ฌ๋ฌ ์กฐ๊ฑด ์ฒ๋ฆฌ
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'D'
# ์ค์ฒฉ ์กฐ๊ฑด๋ฌธ
if score >= 60:
if score >= 90:
grade = 'A'
else:
grade = 'B'
else:
grade = 'F'
โ elif ํน์ง:
- ์ฌ๋ฌ ๊ฐ์ ์กฐ๊ฑด ์ฒ๋ฆฌ ๊ฐ๋ฅ
- if๋ฌธ ๋ค์์๋ง ์ฌ์ฉ ๊ฐ๋ฅ
- else๋ฌธ ์ด์ ์ ์์น
# ์ผ๋ฐ์ ์ธ if-else๋ฌธ
if score >= 60:
message = "ํฉ๊ฒฉ"
else:
message = "๋ถํฉ๊ฒฉ"
# ์กฐ๊ฑด๋ถ ํํ์
message = "ํฉ๊ฒฉ" if score >= 60 else "๋ถํฉ๊ฒฉ"
# ์ค์ฒฉ ์กฐ๊ฑด๋ถ ํํ์
grade = 'A' if score >= 90 else 'B' if score >= 80 else 'C'
โ ์ฅ์ :
- ์ฝ๋ ๊ฐ๊ฒฐ์ฑ
- ๊ฐ๋ ์ฑ ํฅ์
- ํ ์ค๋ก ํํ ๊ฐ๋ฅ
# ์๋ฌด๊ฒ๋ ํ์ง ์์ ๋
if condition:
pass
else:
print("์กฐ๊ฑด์ด ๊ฑฐ์ง์ผ ๋ ์คํ")
# ํจ์๋ ํด๋์ค ์ ์์ ์์ ์ฝ๋
def my_function():
pass
class MyClass:
pass
โ pass ์ฌ์ฉ:
- ์์ ์ฝ๋ ์์ฑ์
- ์กฐ๊ฑด๋ฌธ์์ ์คํํ ์ฝ๋๊ฐ ์์ ๋
- ๊ตฌ๋ฌธ์ ์ผ๋ก ๋ฌธ์ฅ์ด ํ์ํ์ง๋ง ํ๋ก๊ทธ๋จ ์คํ์๋ ์ํฅ์ ์ฃผ์ง ์์ ๋
ํ์ด์ฌ์์๋ ์กฐ๊ฑด์ ์์ฒด๋ฅผ ๊ฐ์ผ๋ก ํ์ฉํ ์ ์๋ค.
# ๋ถ๋ฆฌ์ธ ๊ฐ์ ์ ์๋ก ํ์ฉ
is_valid = True
count = 10 + is_valid # 11 (True๋ 1๋ก ๊ณ์ฐ๋จ)
# ์กฐ๊ฑด์์ ๊ณ์ฐ์์ ํ์ฉ
value = 100
is_greater_than_50 = value > 50 # True
factor = 2 if is_greater_than_50 else 0.5
result = value * factor # 200
# ์กฐ๊ฑด์๊ณผ ๋ฆฌ์คํธ ์ปดํ๋ฆฌํจ์
numbers = [1, 2, 3, 4, 5]
evens = [n for n in numbers if n % 2 == 0] # [2, 4]
odds = [n for n in numbers if n % 2 != 0] # [1, 3, 5]
โ ํน์ง:
- True๋ ์ ์ 1, False๋ ์ ์ 0์ผ๋ก ํ๊ฐ๋จ
- ํจ์ํ ํ๋ก๊ทธ๋๋ฐ ํจํด์ ์ ์ฉ
- ๋ฆฌ์คํธ, ๋์ ๋๋ฆฌ ์ปดํ๋ฆฌํจ์ ๊ณผ ์กฐํฉ ๊ฐ๋ฅ
Python 3.10๋ถํฐ ๋์
๋ match-case
๋ฌธ์ ๋ค๋ฅธ ์ธ์ด์ switch-case์ ์ ์ฌํ์ง๋ง ํจ์ฌ ๊ฐ๋ ฅํ๋ค.
# ๊ธฐ๋ณธ match-case ์ฌ์ฉ๋ฒ
status = 404
match status:
case 200:
print("OK")
case 404:
print("Not Found")
case 500:
print("Server Error")
case _: # ๊ธฐ๋ณธ๊ฐ(default)
print("Unknown status")
# ํจํด ๋งค์นญ ํ์ฉ
def process_command(command):
match command.split():
case ["quit"]:
print("์ข
๋ฃํฉ๋๋ค")
return True
case ["help"]:
print("๋์๋ง์ ํ์ํฉ๋๋ค")
case ["add", *items]:
print(f"์ถ๊ฐ ํญ๋ชฉ: {items}")
case ["delete", item]:
print(f"์ญ์ ํญ๋ชฉ: {item}")
case _:
print("์ ์ ์๋ ๋ช
๋ น์ด์
๋๋ค")
return False
# ๋ฐ์ดํฐ ๊ตฌ์กฐ ๋งค์นญ
def process_point(point):
match point:
case (0, 0):
print("์์ ")
case (0, y):
print(f"Y์ถ ์ง์ : {y}")
case (x, 0):
print(f"X์ถ ์ง์ : {x}")
case (x, y) if x == y:
print(f"๋๊ฐ์ ์ง์ : {x}")
case (x, y):
print(f"์ผ๋ฐ ์ง์ : ({x}, {y})")
# ํด๋์ค ๋งค์นญ
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def classify_point(obj):
match obj:
case Point(x=0, y=0):
print("์์ ")
case Point(x=0, y=y):
print(f"Y์ถ ์ง์ : {y}")
case Point(x=x, y=0):
print(f"X์ถ ์ง์ : {x}")
case Point(x=x, y=y) if x == y:
print(f"๋๊ฐ์ ์ง์ : {x}")
case Point():
print(f"์ผ๋ฐ Point: ({obj.x}, {obj.y})")
case _:
print("Point ๊ฐ์ฒด ์๋")
โ match-case์ ์ฅ์ :
- ๋ค์ํ ํจํด ๋งค์นญ ์ง์
- ๊ตฌ์กฐ ๋ถํด ํ ๋น ๋ด์ฅ
- ๋ฆฌ์คํธ, ํํ, ๊ฐ์ฒด ๋งค์นญ ๊ฐ๋ฅ
- ๊ฐ๋ ์ (guard clause) ์ง์
- ์ฝ๋์ ๊ฐ๋ ์ฑ ํฅ์
์กฐ๊ฑด๋ฌธ์ ํจ์จ์ ์ผ๋ก ์์ฑํ๋ ๋ฐฉ๋ฒ๋ค์ด๋ค.
# ์ค์ฒฉ if๋ฌธ ์ฌ์ฉ
def process_data(data):
if data:
if isinstance(data, list):
if len(data) > 0:
return sum(data)
else:
return 0
else:
return None
else:
return None
# ์กฐ๊ธฐ ๋ฐํ์ ์ฌ์ฉํ ๊ฐ์
def process_data_improved(data):
if not data:
return None
if not isinstance(data, list):
return None
if len(data) == 0:
return 0
return sum(data)
# if-elif ์ฒด์ธ ์ฌ์ฉ
def perform_operation(operation, a, b):
if operation == 'add':
return a + b
elif operation == 'subtract':
return a - b
elif operation == 'multiply':
return a * b
elif operation == 'divide':
return a / b if b != 0 else None
else:
return None
# ๋์คํจ์น ํ
์ด๋ธ์ ์ฌ์ฉํ ๊ฐ์
def add(a, b): return a + b
def subtract(a, b): return a - b
def multiply(a, b): return a * b
def divide(a, b): return a / b if b != 0 else None
operations = {
'add': add,
'subtract': subtract,
'multiply': multiply,
'divide': divide
}
def perform_operation_improved(operation, a, b):
if operation not in operations:
return None
return operations[operation](a, b)
def calculate_discount(order_total, user_status):
# ๋ณต์กํ ์ค์ฒฉ ์กฐ๊ฑด๋ฌธ
if user_status == 'premium':
if order_total >= 100:
discount = 0.2
else:
discount = 0.1
elif user_status == 'regular':
if order_total >= 200:
discount = 0.15
else:
discount = 0.05
else:
discount = 0
return order_total * (1 - discount)
# ๊ฐ๋ ์ ์ ์ฌ์ฉํ ๊ฐ์
def calculate_discount_improved(order_total, user_status):
# ๊ธฐ๋ณธ๊ฐ ์ค์
discount = 0
# ํ๋ฆฌ๋ฏธ์ ํ์ ์ฒ๋ฆฌ
if user_status == 'premium':
discount = 0.1
if order_total >= 100:
discount = 0.2
return order_total * (1 - discount)
# ์ผ๋ฐ ํ์ ์ฒ๋ฆฌ
if user_status == 'regular':
discount = 0.05
if order_total >= 200:
discount = 0.15
return order_total * (1 - discount)
# ๋นํ์ ์ฒ๋ฆฌ
return order_total
โ ํจ์จ์ ์ธ ์กฐ๊ฑด๋ฌธ ํจํด ํน์ง:
- ์ค์ฒฉ ๊น์ด๋ฅผ ์ค์ฌ ๊ฐ๋ ์ฑ ํฅ์
- ์ ์ง๋ณด์ ์ฉ์ด์ฑ ์ฆ๊ฐ
- ์ฑ๋ฅ ํฅ์ (๋ถํ์ํ ์กฐ๊ฑด ๊ฒ์ฌ ๋ฐฉ์ง)
- ์ฝ๋ ์ค๋ณต ๊ฐ์
- ํ์ฅ์ฑ ์ฆ๊ฐ
# ํจ์จ์ ์ธ ๋จ๋ฝ ํ๊ฐ
def is_valid_user(user):
# user๊ฐ None์ด๋ฉด user_id ์ ๊ทผ ์ ์ False ๋ฐํ
return user is not None and user.get('id') is not None
# ๋ฐ์ดํฐ๋ฒ ์ด์ค ์กฐํ๋ ๋น์ฉ์ด ๋์ ์์
์ด๋ฏ๋ก ๋ง์ง๋ง์ ๋ฐฐ์น
def can_access_resource(user, resource_id):
if not user:
return False
if not resource_id:
return False
if not user.is_active:
return False
# ๋น์ฉ์ด ๋์ DB ์กฐํ๋ ๋ค๋ฅธ ์กฐ๊ฑด์ ๋ง์กฑํ ํ์ ๋ง์ง๋ง์ผ๋ก ์ํ
return database.has_permission(user.id, resource_id)
# ์กฐ๊ฑด ๊ฒ์ฌ ์์๊ฐ ์ค์ํ ์ํฉ
def process_event(event):
# 1. ๊ฐ์ฅ ์์ฃผ ๋ฐ์ํ๋ ์กฐ๊ฑด์ ๋จผ์ ๊ฒ์ฌ (๋น๋ ๊ธฐ๋ฐ ์ต์ ํ)
if event.type == 'COMMON_EVENT':
return handle_common_event(event)
# 2. ๊ณ์ฐ ๋น์ฉ์ด ์ ์ ์กฐ๊ฑด์ ๋จผ์ ๊ฒ์ฌ (๋น์ฉ ๊ธฐ๋ฐ ์ต์ ํ)
if not is_valid_format(event): # ๊ฐ๋จํ ํ์ ๊ฒ์ฌ
return {'error': 'Invalid format'}
# 3. ๋ณต์กํ ๊ฒ์ฆ ๋ก์ง์ ๋์ค์ ์คํ
if not is_authorized(event): # ๋ณต์กํ ๊ถํ ๊ฒ์ฌ
return {'error': 'Unauthorized'}
# 4. ๋ฐ์ดํฐ๋ฒ ์ด์ค ์กฐํ ๊ฐ์ ๋น์ฉ์ด ๋์ ์์
์ ๋ง์ง๋ง์
return process_in_database(event)
# ๋ฆฌ์คํธ๋ฅผ ์ฌ์ฉํ ๋ฉค๋ฒ์ญ ๊ฒ์ฌ (O(n) ์๊ฐ ๋ณต์ก๋)
valid_statuses = ['active', 'pending', 'suspended']
if user_status in valid_statuses:
process_user()
# ์ธํธ๋ฅผ ์ฌ์ฉํ ๋ฉค๋ฒ์ญ ๊ฒ์ฌ (O(1) ์๊ฐ ๋ณต์ก๋)
valid_statuses = {'active', 'pending', 'suspended'}
if user_status in valid_statuses:
process_user()
# ๋์
๋๋ฆฌ๋ฅผ ์ฌ์ฉํ ์กฐ๊ฑด ๋ถ๊ธฐ (O(1) ์ ๊ทผ)
handlers = {
'active': handle_active_user,
'pending': handle_pending_user,
'suspended': handle_suspended_user
}
if user_status in handlers:
handlers[user_status](user)
โ ์ฑ๋ฅ ์ต์ ํ ์์น:
- ๊ณ์ฐ ๋น์ฉ์ด ๋ฎ์ ์กฐ๊ฑด์ ๋จผ์ ๊ฒ์ฌ
- ๋ฐ์ ๋น๋๊ฐ ๋์ ์กฐ๊ฑด์ ๋จผ์ ๊ฒ์ฌ
- ์ ์ ํ ์๋ฃ๊ตฌ์กฐ ์ ํ (๋ฆฌ์คํธ vs ์ธํธ vs ๋์ ๋๋ฆฌ)
- ๋จ๋ฝ ํ๊ฐ๋ฅผ ํ์ฉํ์ฌ ๋ถํ์ํ ์ฐ์ฐ ๋ฐฉ์ง
- ์กฐ๊ฑด๋ฌธ๋ณด๋ค ๋์คํจ์น ํ ์ด๋ธ์ด ํจ์จ์ ์ธ ๊ฒฝ์ฐ ๊ณ ๋ ค
# ์ค์ ๊ฐ์ ์ฝ๋ ์์ (ํ๊ฒฝ๋ณ์ โ ์ค์ ํ์ผ โ ๊ธฐ๋ณธ๊ฐ)
def get_config(key, default=None):
# ํ๊ฒฝ ๋ณ์์์ ๋จผ์ ํ์ธ
env_var = os.environ.get(f'APP_{key.upper()}')
if env_var is not None:
return env_var
# ์ค์ ํ์ผ์์ ํ์ธ
if config and key in config:
return config[key]
# ๊ธฐ๋ณธ๊ฐ ์ฌ์ฉ
return default
def calculate_investment_return(principal, rate, years):
# ์
๋ ฅ๊ฐ ์ ํจ์ฑ ๊ฒ์ฌ
if not isinstance(principal, (int, float)) or principal <= 0:
raise ValueError("์๊ธ์ ์์์ฌ์ผ ํฉ๋๋ค")
if not isinstance(rate, (int, float)) or rate < 0:
raise ValueError("์ด์จ์ 0 ์ด์์ด์ด์ผ ํฉ๋๋ค")
if not isinstance(years, (int, float)) or years <= 0:
raise ValueError("๊ธฐ๊ฐ์ ์์์ฌ์ผ ํฉ๋๋ค")
# ๊ณ์ฐ ๋ก์ง
return principal * ((1 + rate/100) ** years)
class OrderState:
CREATED = 'created'
PAID = 'paid'
SHIPPED = 'shipped'
DELIVERED = 'delivered'
CANCELED = 'canceled'
class Order:
def __init__(self):
self.state = OrderState.CREATED
def pay(self):
if self.state == OrderState.CREATED:
self.state = OrderState.PAID
return True
return False
def ship(self):
if self.state == OrderState.PAID:
self.state = OrderState.SHIPPED
return True
return False
def deliver(self):
if self.state == OrderState.SHIPPED:
self.state = OrderState.DELIVERED
return True
return False
def cancel(self):
if self.state in (OrderState.CREATED, OrderState.PAID):
self.state = OrderState.CANCELED
return True
return False
from contextlib import contextmanager
@contextmanager
def conditionally_log(condition, logger):
"""์กฐ๊ฑด๋ถ ๋ก๊น
์ ์ํ ์ปจํ
์คํธ ๊ด๋ฆฌ์"""
if condition:
logger.info("์์
์์")
try:
yield
logger.info("์์
์ฑ๊ณต ์๋ฃ")
except Exception as e:
logger.error(f"์์
์คํจ: {e}")
raise
else:
yield # ๋ก๊น
์์ด ์คํ
# ์ฌ์ฉ ์์
import logging
logger = logging.getLogger('app')
debug_mode = True
with conditionally_log(debug_mode, logger):
# ์์
์ํ
result = process_data()
โ ์ค์ ํจํด ์ฅ์ :
- ์ฝ๋ ์ฌ์ฌ์ฉ์ฑ ์ฆ๊ฐ
- ์ค๋ฅ ์ฒ๋ฆฌ ๊ฐ์
- ์ ์ง๋ณด์ ์ฉ์ด์ฑ ํฅ์
- ๊ฐ๋ ์ฑ ๋ฐ ํ์ฅ์ฑ ์ฆ๊ฐ
- ์ํฉ๋ณ ์ ์ ํ ๋์ ๊ฐ๋ฅ