Python 문법 심화 강의를 모두 수강했다.
많은 내용이 있었지만 생소하거나 헷갈리는 것들 위주로 정리해 보았다.
naming convension
Class - Pascal 표기법(ex. PythonIsVeryGood)
variable, 함수 - Snake 표기법(ex. python_is_very_food)
all() / any() 함수
# all() : 요소들이 모두 True일 때, return true
if all([True, True, True, False, True]):
print("pass!") # False가 존재하기 때문에 통과X
# any() : 요소들 중 하나라도 True일 때, return true
if any([False, False, False, True, False]):
print("pass!") # True가 1개 이상 존재하기 때문에 통과O
list.sort() / sorted
# sort
sample_list = [3, 2, 4, 1, 5]
sample_list.sort() # return data 없이 list 자체를 정렬
print(sample_list) # [1, 2, 3, 4, 5]
# sorted
sample_list = [3, 2, 4, 1, 5]
sorted_list = sorted(sample_list) # 정렬 된 list를 return
print(sorted_list) # [1, 2, 3, 4, 5]
# 잘못된 방법
sample_list = [3, 2, 4, 1, 5]
sorted_list = sample_list.sort() # .sort()의 return data는 None
print(sorted_list) # None
return type이 무엇인지는 google search를 하거나 docstring을 확인 하거나 함수 구현 코드를 확인하면 된다.
paking / unpacking:
요소를 묶어주거나 풀어주는 것. list나 dictionary 값을 함수에 입력할 때 주로 사용
def add(*args):
result = 0
for i in args:
result += i
return result
numbers = [1, 2, 3, 4] #list
print(add(*numbers))
print(add(1, 2, 3, 4)) #두 개의 print 값이 10으로 같음
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 = { #dictionary
"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'
}
"""
regex
regular expression의 약자, 문자열이 특정 패턴과 일치하는지 판단하는 형식 언어
따라서 email에 맞는 형식인지, 유효한 핸드폰 번호인지 등을 판단하는 데에 사용할 수 있음
참고 site: https://regexr.com/
regex 사용해 email format check
from pprint import pprint
import re
# rstring : backslash(\)를 문자 그대로 표현
# ^[\w\.-]+@([\w-]+\.)+[\w-]{2,4}$ : 이메일 검증을 위한 정규표현식 코드
email_regex = re.compile(r"^[\w\.-]+@([\w-]+\.)+[\w-]{2,4}$")
def verify_email(email):
return bool(email_regex.fullmatch(email))
test_case = [
"apple", # False
"sparta@regex", # False
"$parta@regex.com", # False
"sparta@re&ex.com", # False
"spar_-ta@regex.com", # True
"sparta@regex.co.kr", # True
"sparta@regex.c", # False
"sparta@regex.cooom", # False
"@regex.com", # False
]
result = [{x: verify_email(x)} for x in test_case]
pprint(result)
decorator
python의 함수를 장식해주는 역할
@decorator 형태로 사용, 해당 함수가 실행될 때 decorator도 같이 실행
def double_number(func):
def wrapper(a, b):
double_a = a * 2
double_b = b * 2
return func(double_a, double_b)
return wrapper
@double_number
def double_number_add(a, b):
return a + b
def add(a, b):
return a + b
print(double_number_add(5, 10))
print(add(5, 10)) #result output 순서대로 30과 15
앞으로 직접 웹사이트를 만들어보며 위의 문법들에 좀 더 익숙해져야 겠다.
생각해보니 지금 금요일 오후다. python 문법 심화 강의를 다 들어서 뿌듯하다.
LIST
'Computer Programming > AI' 카테고리의 다른 글
TIL_Python Assignment 1(Up-and-Down Game) (0) | 2023.08.21 |
---|---|
WIL_두 번째 주 (0) | 2023.08.20 |
TIL_Python 문법 심화와 환경 세팅 (1) | 2023.08.17 |
TIL_Python flask를 이용한 app.py와 index.html 세팅 (0) | 2023.08.16 |
TIL_python grammer basic (0) | 2023.08.14 |