자주 사용되는 모듈 및 패턴
type() / 값의 자료형 확인해 보기
integer = 10
float_ = 1.23
string = "hello world!!"
list_ = [1, 2, 3]
tuple_ = (1, 2, 3)
set_ = {1, 2, 3}
dictionary = {"key": "value"}
boolean = True
print(type(integer)) # <class 'int'>
print(type(float_)) # <class 'float'>
print(type(string)) # <class 'str'>
print(type(list_)) # <class 'list'>
print(type(tuple_)) # <class 'tuple'>
print(type(set_)) # <class 'set'>
print(type(dictionary)) # <class 'dict'>
print(type(boolean)) # <class 'bool'>
split() / string을 list로 변환하기
# split은 string.split("구분자")로 구성되어 있습니다.
string = "hello/python/world!!"
string_list = string.split("/") # split() 안에 들어간 값을 기준으로 문자를 나눈다.
print(string_list) # ['hello', 'python', 'world!!']
join() / list를 string으로 변환하기
# join은 "사이에 들어갈 문자".join(리스트) 로 구성되어 있습니다.
string_list = ["hello", "python", "world"]
string = "!! ".join(string_list)
print(string) # hello!! python!! world
replace() / 문자열 바꾸기
# replace는 "변경할 문자".replace("변경 전 문자", "변경 후 문자")로 구성되어 있습니다.
before_string = "hello world!!!"
after_string = before_string.replace("!", "~") # !를 ~로 변경
print(after_string) # hello world~~~
pprint() / 코드 예쁘게 출력하기 (from pprint import pprint 입력 필수)
# pprint는 pretty print의 약자이며, 데이터를 더 예쁘게 출력해 줍니다.
from pprint import pprint
sample_data = {
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{"id": "1001", "type": "Regular"},
{"id": "1002", "type": "Chocolate"},
{"id": "1003", "type": "Blueberry"},
{"id": "1004", "type": "Devil's Food"}
]
},
"topping":
[
{"id": "5001", "type": "None"},
{"id": "5002", "type": "Glazed"},
{"id": "5005", "type": "Sugar"},
{"id": "5007", "type": "Powdered Sugar"},
{"id": "5006", "type": "Chocolate with Sprinkles"},
{"id": "5003", "type": "Chocolate"},
{"id": "5004", "type": "Maple"}
]
}
pprint(sample_data) # print로 출력했을 때와 결과 비교해 보기!!
random / 랜덤 한 로직이 필요할 때 (import random 입력 필수)
# 난수 생성, 임의의 번호 생성 등 랜덤한 동작이 필요할 때 사용
import random
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
random.shuffle(numbers) # numbers를 무작위하게 섞기
print(numbers) # [2, 8, 6, 4, 3, 7, 1, 5]
random_number = random.randint(1, 10) # 1 ~ 10 사이의 무작위 번호 생성
print(random_number) # 4
time / 시간 다루기(import time 입력 필수)
import time
start_time = time.time() # 현재 시간 저장
time.sleep(1) # 1초간 대기
end_time = time.time()
# 코드가 종료된 시간 - 코드가 시작된 시간으로 실행 시간 구하기 (단위 : 초)
print(f"코드 실행 시간 : {end_time-start_time:.5f}") # 코드 실행 시간 : 1.00100
{end_time-start_time:. 5f}. 5f는 소수점 다섯째 자리 까지라는 뜻
datetime / 날짜 다루기 (from datetime import datetime, timedelta 입력 필수)
from datetime import datetime, timedelta
# 현재 날짜 및 시간 출력
print(datetime.now()) # 2023-02-22 15:55:32.277095
# datetime의 format code 더 제세한건 여기서 확인 가능합니다.
'''
%y : 두 자리 연도 / 20, 21, 22
%Y : 네 자리 연도 / 2020, 2021, 2022
%m : 두 자리 월 / 01, 02 ... 11 ,12
%d : 두 자리 일 / 01, 02 ... 30, 31
%I : 12시간제 시간 / 01, 02 ... 12
%H : 24시간제의 시간 / 00, 01 ... 23
%M : 두 자리 분 / 00, 01 ... 58, 59
%S : 두 자리 초 / 00, 01 ... 58, 59
'''
# string을 datetime 날짜로 변경하기
string_datetime = "23/12/25 13:20"
datetime_ = datetime.strptime(string_datetime, "%y/%m/%d %H:%M")
print(datetime_) # 2023-12-25 13:20:00
# datetime 날짜를 string으로 변환하기
now = datetime.now()
string_datetime = datetime.strftime(now, "%y/%m/%d %H:%M:%S")
print(string_datetime) # 22/09/04 04:04
# 3일 전 날짜 구하기
three_days_ago = datetime.now() - timedelta(days=3)
print(three_days_ago) # 2023-02-19 16:27:52.526502
조건문 심화
조건문 부등호
'''== : 값이 일치하는지 비교'''
"a" == "a" # True
"a" == "b" # False
1 == "1" # False, 값은 동일하지만 자료형이 다르기 때문
'''!= : 값이 일치하지 않는지 비교'''
0 != 1 # True
0 != 0 # False
'''>, < : 값이 큰지 작은지 비교'''
5 > 2 # True
1 < 0 # False
1 > 1 # False
'''>=, <= : 값이 크거나 같은지, 작거나 같은지 비교'''
1 >= 1 # True
'''in : 특정 값이 list / tuple / set에 포함되어 있는지 확인'''
4 in [1, 2, 3] # False
1 in (1, 2, 3) # True
# 모든 비교 연산자의 결과는 print()로 확인할 수 있습니다.
print(1 == 1) # True
특정 비교 결과 혹은 값이 True 혹은 False일 경우 실행될 로직을 정의합니다.
if condition: # 조건이 True일 경우
# some code
# not 키워드를 사용할 경우 조건이 False일 때 실행됩니다.
elif not condition: # 조건이 False일 경우
# some code
else: # 위 조건들 중 만족하는게 없을 경우
# some code
and, or을 사용해 2개 이상의 조건을 복합적으로 사용할 수 있습니다.
if condition1 and condition2: # 두 조건을 모두 만족할 경우
# some code
elif condition or condition: # 두 조건 중 하나라도 만족할 경우
# some code
else:
# some code
비어있는 string, list 등은 분기문에서 False로 판단합니다.
empty_string = ""
empty_list = []
if not empty_string:
print("string is empty!!")
if not empty_list:
print("list is empty!!")
특정 값이 True인지 False인지는 bool() 함수를 사용해 확인할 수 있습니다.
print(bool(""))
print(bool(0))
print(bool([]))
print(bool("sample"))
print(bool([1, 2]))
print(bool(1))
print(bool(-1)) # 0이 아닌 숫자는 True로 판단
# sample result
"""
False
False
False
True
True
True
True
"""
any() 혹은 all() 함수를 사용해 여러 값들에 대한 조건을 판단할 수 있습니다.
# all() : 요소들이 모두 True일 경우 True 리턴
if all([True, True, True, False, True]):
print("통과!") # False가 존재하기 때문에 분기문을 통과하지 못함
# any() : 요소들 중 하나라도 True일 경우 True 리턴
if any([False, False, False, True, False]):
print("통과!") # True가 1개 이상 존재하기 때문에 분기문을 통과함
리턴 타입에 따른 활용 방법
# 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
sort()와 sorted의 차이는 변수를 그대로 쓰냐 아니면 새로운 변수를 사용하냐의 차이로 볼 수 있다.
내가 모르는 함수를 사용하는 방법을 찾아보는 법
( 내가 사용하는 코드의 리턴 타입을 확인하는 방법)
1. 검색
google에 python 함수명과 같은 형태로 검색해서 해당 기능을 어떻게 사용해야 하는지 확인합니다.
단순하게 검색하려는 함수를 어떻게 사용하는지에 대한 내용은 한글로 검색해도 되지만 더 많은 정보를 얻고 싶다면 영어로 검색하시는 것을 권장드립니다.
2. docstring 확인 (함수를 만든 사람이 적은 설명 보기)
함수를 작성할 때 docstring을 활용하면 사용하려는 함수가 어떤 역할을 하는지, 어떤 값을 인자로 받는지, 어떤 값을 리턴해주는지 확인할 수 있습니다.

3. 함수 구현 코드 확인 (import 함수로 직접 찾아가서 어떻게 만들어졌는지 알여주는 걸)
내장함수의 경우 c언어로 컴파일되어 있는 경우가 많아 때문에 해당하지 않을 수 있지만, 특히 외부 라이브러리를 import 해서 사용할 때는 구현부의 코드를 보고 사용 방법을 익히는 것도 좋은 방법입니다.

vscode에서 사용하는 함수를 ctrl + click 하면 구현 코드를 확인할 수 있습니다.
에러상황시 조치방법
python에서는 try / except 문법을 사용해 에러가 발생했을 때 처리를 해줄 수 있습니다.
number = "num"
try: # try 구문 안에서 에러가 발생할 경우 except로 넘어감
number = int(number) # "num"을 숫자로 바꾸는 과정에서 에러 발생
except: # 에러가 발생했을 때 처리
print(f"{number}은(는) 숫자가 아닙니다.")
에러 종류에 따라 다른 로직 처리
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와 같이 연달아서 작성할 수 있습니다.

except 뒤에 붙여 주어야 하는 오류 명이 무엇인지 모를 때에는 실행했을 때 오류 명을 자세히 보면 된다.

빨간 박스처럼 오류의 명이 나오는데 그걸 복사해서 붙여 넣어주면 조건이 완성된다.
그 외에 오류


패킹과 언패킹
패킹(packing)과 언패킹(unpacking)은 단어의 뜻 그대로
요소들을 묶어주거나 풀어주는 것을 의미합니다.
list 혹은 dictionary의 값을 함수에 입력할 때 주로 사용됩니다.
*args와 **kwargs이 그것들이다.
list에서의 활용
def add(*args):
result = 0
for i in args:
result += i
return result
numbers = [1, 2, 3, 4]
print(add(*numbers))
""" 아래 코드와 동일
print(add(1, 2, 3, 4))
"""
# result output
"""
10
"""
list인 numbers를 함수에 넣을 때 리스트가 아니 하나의 숫자씩 풀어서 넣기 위해 *을 붙여 *numbers로 입력을 하면
괄호가 없는 숫자가 전부 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'
}
"""
딕셔너리 또한 안에 내용을 따로따로 풀어서 표시하는 것이 가능하다.



kwargs.get = kwargs라는 딕셔너리에서
name 키의 value값이 있다면 value값을 넣어주고
없다면 '-'으로 출력값을 넣어주고
그 값을 profile의 name키 값에 넣어준다.
args와 kwargs 전부 넣어 줄 수 있다.


'코딩 정리함' 카테고리의 다른 글
모의 면접 준비 (0) | 2024.04.16 |
---|---|
정렬은 어떻게 하는 것 일까? (1) | 2024.03.06 |
유용한 파이썬 정보 (사이트, 확장프로그램) (0) | 2024.02.20 |
GIT 명령어 모음 (0) | 2024.02.18 |
SQL 명령어 모음 (0) | 2024.02.16 |
자주 사용되는 모듈 및 패턴
type() / 값의 자료형 확인해 보기
integer = 10
float_ = 1.23
string = "hello world!!"
list_ = [1, 2, 3]
tuple_ = (1, 2, 3)
set_ = {1, 2, 3}
dictionary = {"key": "value"}
boolean = True
print(type(integer)) # <class 'int'>
print(type(float_)) # <class 'float'>
print(type(string)) # <class 'str'>
print(type(list_)) # <class 'list'>
print(type(tuple_)) # <class 'tuple'>
print(type(set_)) # <class 'set'>
print(type(dictionary)) # <class 'dict'>
print(type(boolean)) # <class 'bool'>
split() / string을 list로 변환하기
# split은 string.split("구분자")로 구성되어 있습니다.
string = "hello/python/world!!"
string_list = string.split("/") # split() 안에 들어간 값을 기준으로 문자를 나눈다.
print(string_list) # ['hello', 'python', 'world!!']
join() / list를 string으로 변환하기
# join은 "사이에 들어갈 문자".join(리스트) 로 구성되어 있습니다.
string_list = ["hello", "python", "world"]
string = "!! ".join(string_list)
print(string) # hello!! python!! world
replace() / 문자열 바꾸기
# replace는 "변경할 문자".replace("변경 전 문자", "변경 후 문자")로 구성되어 있습니다.
before_string = "hello world!!!"
after_string = before_string.replace("!", "~") # !를 ~로 변경
print(after_string) # hello world~~~
pprint() / 코드 예쁘게 출력하기 (from pprint import pprint 입력 필수)
# pprint는 pretty print의 약자이며, 데이터를 더 예쁘게 출력해 줍니다.
from pprint import pprint
sample_data = {
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{"id": "1001", "type": "Regular"},
{"id": "1002", "type": "Chocolate"},
{"id": "1003", "type": "Blueberry"},
{"id": "1004", "type": "Devil's Food"}
]
},
"topping":
[
{"id": "5001", "type": "None"},
{"id": "5002", "type": "Glazed"},
{"id": "5005", "type": "Sugar"},
{"id": "5007", "type": "Powdered Sugar"},
{"id": "5006", "type": "Chocolate with Sprinkles"},
{"id": "5003", "type": "Chocolate"},
{"id": "5004", "type": "Maple"}
]
}
pprint(sample_data) # print로 출력했을 때와 결과 비교해 보기!!
random / 랜덤 한 로직이 필요할 때 (import random 입력 필수)
# 난수 생성, 임의의 번호 생성 등 랜덤한 동작이 필요할 때 사용
import random
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
random.shuffle(numbers) # numbers를 무작위하게 섞기
print(numbers) # [2, 8, 6, 4, 3, 7, 1, 5]
random_number = random.randint(1, 10) # 1 ~ 10 사이의 무작위 번호 생성
print(random_number) # 4
time / 시간 다루기(import time 입력 필수)
import time
start_time = time.time() # 현재 시간 저장
time.sleep(1) # 1초간 대기
end_time = time.time()
# 코드가 종료된 시간 - 코드가 시작된 시간으로 실행 시간 구하기 (단위 : 초)
print(f"코드 실행 시간 : {end_time-start_time:.5f}") # 코드 실행 시간 : 1.00100
{end_time-start_time:. 5f}. 5f는 소수점 다섯째 자리 까지라는 뜻
datetime / 날짜 다루기 (from datetime import datetime, timedelta 입력 필수)
from datetime import datetime, timedelta
# 현재 날짜 및 시간 출력
print(datetime.now()) # 2023-02-22 15:55:32.277095
# datetime의 format code 더 제세한건 여기서 확인 가능합니다.
'''
%y : 두 자리 연도 / 20, 21, 22
%Y : 네 자리 연도 / 2020, 2021, 2022
%m : 두 자리 월 / 01, 02 ... 11 ,12
%d : 두 자리 일 / 01, 02 ... 30, 31
%I : 12시간제 시간 / 01, 02 ... 12
%H : 24시간제의 시간 / 00, 01 ... 23
%M : 두 자리 분 / 00, 01 ... 58, 59
%S : 두 자리 초 / 00, 01 ... 58, 59
'''
# string을 datetime 날짜로 변경하기
string_datetime = "23/12/25 13:20"
datetime_ = datetime.strptime(string_datetime, "%y/%m/%d %H:%M")
print(datetime_) # 2023-12-25 13:20:00
# datetime 날짜를 string으로 변환하기
now = datetime.now()
string_datetime = datetime.strftime(now, "%y/%m/%d %H:%M:%S")
print(string_datetime) # 22/09/04 04:04
# 3일 전 날짜 구하기
three_days_ago = datetime.now() - timedelta(days=3)
print(three_days_ago) # 2023-02-19 16:27:52.526502
조건문 심화
조건문 부등호
'''== : 값이 일치하는지 비교'''
"a" == "a" # True
"a" == "b" # False
1 == "1" # False, 값은 동일하지만 자료형이 다르기 때문
'''!= : 값이 일치하지 않는지 비교'''
0 != 1 # True
0 != 0 # False
'''>, < : 값이 큰지 작은지 비교'''
5 > 2 # True
1 < 0 # False
1 > 1 # False
'''>=, <= : 값이 크거나 같은지, 작거나 같은지 비교'''
1 >= 1 # True
'''in : 특정 값이 list / tuple / set에 포함되어 있는지 확인'''
4 in [1, 2, 3] # False
1 in (1, 2, 3) # True
# 모든 비교 연산자의 결과는 print()로 확인할 수 있습니다.
print(1 == 1) # True
특정 비교 결과 혹은 값이 True 혹은 False일 경우 실행될 로직을 정의합니다.
if condition: # 조건이 True일 경우
# some code
# not 키워드를 사용할 경우 조건이 False일 때 실행됩니다.
elif not condition: # 조건이 False일 경우
# some code
else: # 위 조건들 중 만족하는게 없을 경우
# some code
and, or을 사용해 2개 이상의 조건을 복합적으로 사용할 수 있습니다.
if condition1 and condition2: # 두 조건을 모두 만족할 경우
# some code
elif condition or condition: # 두 조건 중 하나라도 만족할 경우
# some code
else:
# some code
비어있는 string, list 등은 분기문에서 False로 판단합니다.
empty_string = ""
empty_list = []
if not empty_string:
print("string is empty!!")
if not empty_list:
print("list is empty!!")
특정 값이 True인지 False인지는 bool() 함수를 사용해 확인할 수 있습니다.
print(bool(""))
print(bool(0))
print(bool([]))
print(bool("sample"))
print(bool([1, 2]))
print(bool(1))
print(bool(-1)) # 0이 아닌 숫자는 True로 판단
# sample result
"""
False
False
False
True
True
True
True
"""
any() 혹은 all() 함수를 사용해 여러 값들에 대한 조건을 판단할 수 있습니다.
# all() : 요소들이 모두 True일 경우 True 리턴
if all([True, True, True, False, True]):
print("통과!") # False가 존재하기 때문에 분기문을 통과하지 못함
# any() : 요소들 중 하나라도 True일 경우 True 리턴
if any([False, False, False, True, False]):
print("통과!") # True가 1개 이상 존재하기 때문에 분기문을 통과함
리턴 타입에 따른 활용 방법
# 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
sort()와 sorted의 차이는 변수를 그대로 쓰냐 아니면 새로운 변수를 사용하냐의 차이로 볼 수 있다.
내가 모르는 함수를 사용하는 방법을 찾아보는 법
( 내가 사용하는 코드의 리턴 타입을 확인하는 방법)
1. 검색
google에 python 함수명과 같은 형태로 검색해서 해당 기능을 어떻게 사용해야 하는지 확인합니다.
단순하게 검색하려는 함수를 어떻게 사용하는지에 대한 내용은 한글로 검색해도 되지만 더 많은 정보를 얻고 싶다면 영어로 검색하시는 것을 권장드립니다.
2. docstring 확인 (함수를 만든 사람이 적은 설명 보기)
함수를 작성할 때 docstring을 활용하면 사용하려는 함수가 어떤 역할을 하는지, 어떤 값을 인자로 받는지, 어떤 값을 리턴해주는지 확인할 수 있습니다.

3. 함수 구현 코드 확인 (import 함수로 직접 찾아가서 어떻게 만들어졌는지 알여주는 걸)
내장함수의 경우 c언어로 컴파일되어 있는 경우가 많아 때문에 해당하지 않을 수 있지만, 특히 외부 라이브러리를 import 해서 사용할 때는 구현부의 코드를 보고 사용 방법을 익히는 것도 좋은 방법입니다.

vscode에서 사용하는 함수를 ctrl + click 하면 구현 코드를 확인할 수 있습니다.
에러상황시 조치방법
python에서는 try / except 문법을 사용해 에러가 발생했을 때 처리를 해줄 수 있습니다.
number = "num"
try: # try 구문 안에서 에러가 발생할 경우 except로 넘어감
number = int(number) # "num"을 숫자로 바꾸는 과정에서 에러 발생
except: # 에러가 발생했을 때 처리
print(f"{number}은(는) 숫자가 아닙니다.")
에러 종류에 따라 다른 로직 처리
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와 같이 연달아서 작성할 수 있습니다.

except 뒤에 붙여 주어야 하는 오류 명이 무엇인지 모를 때에는 실행했을 때 오류 명을 자세히 보면 된다.

빨간 박스처럼 오류의 명이 나오는데 그걸 복사해서 붙여 넣어주면 조건이 완성된다.
그 외에 오류


패킹과 언패킹
패킹(packing)과 언패킹(unpacking)은 단어의 뜻 그대로
요소들을 묶어주거나 풀어주는 것을 의미합니다.
list 혹은 dictionary의 값을 함수에 입력할 때 주로 사용됩니다.
*args와 **kwargs이 그것들이다.
list에서의 활용
def add(*args):
result = 0
for i in args:
result += i
return result
numbers = [1, 2, 3, 4]
print(add(*numbers))
""" 아래 코드와 동일
print(add(1, 2, 3, 4))
"""
# result output
"""
10
"""
list인 numbers를 함수에 넣을 때 리스트가 아니 하나의 숫자씩 풀어서 넣기 위해 *을 붙여 *numbers로 입력을 하면
괄호가 없는 숫자가 전부 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'
}
"""
딕셔너리 또한 안에 내용을 따로따로 풀어서 표시하는 것이 가능하다.



kwargs.get = kwargs라는 딕셔너리에서
name 키의 value값이 있다면 value값을 넣어주고
없다면 '-'으로 출력값을 넣어주고
그 값을 profile의 name키 값에 넣어준다.
args와 kwargs 전부 넣어 줄 수 있다.


'코딩 정리함' 카테고리의 다른 글
모의 면접 준비 (0) | 2024.04.16 |
---|---|
정렬은 어떻게 하는 것 일까? (1) | 2024.03.06 |
유용한 파이썬 정보 (사이트, 확장프로그램) (0) | 2024.02.20 |
GIT 명령어 모음 (0) | 2024.02.18 |
SQL 명령어 모음 (0) | 2024.02.16 |