👉 파이썬 문법(이창호 튜터님)
👉 파이썬 과제(클래스 활용, try/except, 리스트 필터 및 정렬)
1) 인자에 기본값 지정해주기
# 함수를 선언할 때 인자에 기본값을 지정해줄 수 있다.
EXPRESSION = {
0: lambda x, y: x + y ,
1: lambda x, y: x - y ,
2: lambda x, y: x * y ,
3: lambda x, y: x / y
}
def calc(num1, num2, option=None): # 인자로 option이 들어오지 않는 경우 기본값 할당
"""
option
- 0: 더하기
- 1: 빼기
- 2: 곱하기
- 3: 나누기
"""
return EXPRESSION[option](num1, num2) if option in EXPRESSION.keys() else False
print(calc(10, 20)) # False
print(calc(10, 20, 0)) # 30
print(calc(10, 20, 1)) # -10
print(calc(10, 20, 2)) # 200
print(calc(10, 20, 3)) # 0.5
2) args / kwargs에 대한 이해
args(arguments)와 keyword arguments(kwargs)는 함수에서 인자로 받을 값들의 갯수가
불규칙하거나 많을 때 주로 사용된다.
인자로 받을 값이 정해져있지 않기 때문에 함수를 더 동적으로 사용할 수 있다.
함수를 선언할 때 args는 앞에 *를 붙여 명시하고, kwargs는 앞에 **를 붙여 명시한다.
number = input()
try:
int(number)
10 / number
except ValueError: # int로 변환하는 과정에서 에러가 발생했을 떄
print(f"{number}은(는) 숫자가 아닙니다.")
except ZeroDivisionError: # 0으로 나누면서 에러가 발생했을 때
print("0으로는 나눌수 없습니다.")
except Exception as e: # 위에서 정의하지 않은 에러가 발생했을 때(권장하지 않음)
print(f"예상하지 못한 에러가 발생했습니다. error : {e}")
# except 문법 또한 if / elif와 같이 연달아서 작성할 수 있다.
def set_profile(**kwargs):
"""
kwargs = {
name: "lee",
gender: "man",
age: 32,
birthday: "01/01",
email: "python@sparta.com"
}
"""
profile = {}
profile["name"] = kwargs.get("name", "-")
profile["gender"] = kwargs.get("gender", "-")
profile["birthday"] = kwargs.get("birthday", "-")
profile["age"] = kwargs.get("age", "-")
profile["phone"] = kwargs.get("phone", "-")
profile["email"] = kwargs.get("email", "-")
return profile
profile = set_profile(
name="lee",
gender="man",
age=32,
birthday="01/01",
email="python@sparta.com",
)
print(profile)
# result print
"""
{
'name': 'lee',
'gender': 'man',
'birthday': '01/01',
'age': 32,
'phone': '-',
'email': 'python@sparta.com'
}
"""
def print_arguments(a, b, *args, **kwargs):
print(a)
print(b)
print(args)
print(kwargs)
print_arguments(
1, # a
2, # b
3, 4, 5, 6, # args
hello="world", keyword="argument" # kwargs
)
# result print
"""
1
2
(3, 4, 5, 6)
{'hello': 'hello', 'world': 'world'}
"""
1) 패킹(packing)과 언패킹(unpacking)은 요소들을 묶어주거나 풀어주는 것. list 혹은 dictionary의 값을 함수에 입력할 때 주로 사용된다.
2) list에서의 활용
def add(*args):
result = 0
for i in args:
result += i
return result
numbers = [1, 2, 3, 4]
print(add(*numbers)) # 10
"""아래 코드와 동일
print(add(1, 2, 3, 4))
"""
3) dictionary에서의 활용
def set_profile(**kwargs):
profile = {}
profile["name"] = kwargs.get("name", "-")
profile["gender"] = kwargs.get("gender", "-")
profile["birthday"] = kwargs.get("birthday", "-")
profile["age"] = kwargs.get("age", "-")
profile["phone"] = kwargs.get("phone", "-")
profile["email"] = kwargs.get("email", "-")
return profile
user_profile = {
"name": "lee",
"gender": "man",
"age": 32,
"birthday": "01/01",
"email": "python@sparta.com",
}
print(set_profile(**user_profile))
""" 아래 코드와 동일
profile = set_profile(
name="lee",
gender="man",
age=32,
birthday="01/01",
email="python@sparta.com",
)
"""
# result print
"""
{
'name': 'lee',
'gender': 'man',
'birthday': '01/01',
'age': 32,
'phone': '-',
'email': 'python@sparta.com'
}
"""
1) 객체지향이란 객체를 모델링하는 방향으로 코드를 작성하는 것을 의미한다.
영어로는 Object-Oriented Programming이라고 하며 앞자를 따 OOP라고 불려진다.
2) 객체 지향의 특성
3) 객체 지향의 장/단점
4) 객체지향 예제 코드
import re
# 숫자, 알파벳으로 시작하고 중간에 - 혹은 _가 포함될 수 있으며 숫자, 알파벳으로 끝나야 한다.
# @
# 알파벳, 숫자로 시작해야 하며 . 뒤에 2자의 알파벳이 와야 한다.
email_regex = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+')
class Attendance:
count = 0
def attendance(self):
self.count += 1
@property
def attendance_count(self):
return self.count
class Profile(Attendance):
def __init__(self, name, age, email):
self.__name = name # __를 붙여주면 class 내부에서만 사용하겠다는 뜻
self.__age = age
self.__email = email
@property # 읽기 전용 속성
def name(self):
return self.__name
@name.setter # 쓰기 전용 속성
def name(self, name):
if isinstance(name, str) and len(name) >= 2:
print("이름은 2자 이상 문자만 입력 가능합니다.")
else:
self.__name = name
@property
def age(self):
return self.__age
@age.setter
def age(self, age):
if isinstance(age, int):
self.__age = age
else:
print("나이에는 숫자만 입력 가능합니다.")
@property
def email(self):
return self.__email
@email.setter
def email(self, email):
if re.fullmatch(email_regex, email):
self.__email = email
else:
print("유효하지 않은 이메일입니다.")
def attendance(self): # override
super().attendance() # 부모 메소드 사용하기
self.count += 1
def __str__(self):
return f"{self.__name} / {self.__age}"
def __repr__(self):
return f"{self.__name}"
⭐ 오늘은 파이썬 심화 강의 마지막 날이다.. 배운 것은 많은데 아직 머리에서 다 정리가 안 된 느낌이다. 과제를 할 때마다 지난 내용까지 다시 보면서 복습중이다. 풀어야 할 과제가 조금 늦게 나와서 그 전까지 파이썬 문법을 복습하고 장고 원격강의를 살짝 들었다. 개념을 탄탄히해서 장고 강의가 시작할 때 적어도 문법 부분에서는 막히는 것이 없었으면 좋겠다😆