- Python 종합 연습
num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]
evens = 0 # 짝수 개수
sum_list = 0 # 리스트 요소 총합
for idx, num in enumerate(num_list):
sum_list += num
# 짝수일 경우 아래 코드 실행
if num % 2 == 0:
print(f"리스트의 {idx}번째 요소 {num}은(는) 짝수 입니다.")
evens += 1
# 리스트 복사 후 내림차순으로 정렬
sorted_list = num_list[:]
sorted_list.sort(reverse=True)
print(f"짝수는 {evens}개 입니다.")
print(f"리스트의 모든 요소의 총합은 {sum_list} 입니다.")
print(f"리스트 안의 요소 중 가장 큰 숫자는 {sorted_list[0]} 입니다.")
- Python 'try - except' 구문
a = list()
try:
# 오류 발생 가능성이 있는 코드
# 주로 connection을 다루는 코드이면 유용
print(a)
except Exception as e:
# Exception에 다양한 종류가 있음
# Exception은 Python의 traceback으로 볼 수 있는 모든 형태의 오류
print(f"오류 발생 (상세: {e})")
else:
# try에서 실행하는 코드에서 오류가 발생하지 않을 경우
print("출력 완료")
finally:
# try -> except/else 까지 모두 거친 후 실행
print("프로그램 종료")
- Python 코드 축약(코드 줄이기)
people = [
{"Name": "Bob", "Sex": "Male", "Age": 15, "Height": 150},
{"Name": "Amy", "Sex": "Female", "Age": 18, "Height": 155},
{"Name": "Greg", "Sex": "Male", "Age": 16, "Height": 160},
{"Name": "Ray", "Sex": "Male", "Age": 22, "Height": 180},
{"Name": "Flora", "Sex": "Female", "Age": 24, "Height": 175},
{"Name": "Evan", "Sex": "Male", "Age": 30, "Height": 170}
]
# 1 기존 if-else 구문
check_male = bool()
if people[0]["Sex"] == "Male":
check_male = True
else:
check_male = False
print(check_male)
# 2 변수로 저장할 필요가 있을 경우 이렇게 한다.
check_male_2 = True if people[1]["Sex"] == "Male" else False
print(check_male_2)
# 3 변수로 저장할 필요가 없다면 바로 쓸 수도 있다.
print(True if people[2]["Sex"] == "Male" else False)
people = [
{"Name": "Bob", "Sex": "Male", "Age": 15, "Height": 150},
{"Name": "Amy", "Sex": "Female", "Age": 18, "Height": 155},
{"Name": "Greg", "Sex": "Male", "Age": 16, "Height": 160},
{"Name": "Ray", "Sex": "Male", "Age": 22, "Height": 180},
{"Name": "Flora", "Sex": "Female", "Age": 24, "Height": 175},
{"Name": "Evan", "Sex": "Male", "Age": 30, "Height": 170}
]
# 성별이 여성인 멤버만 리스트로 정리한다
female_list = list()
# 1 for 문을 통해 list에 append 후 출력
for person in people:
if person["Sex"] == "Female":
female_list.append(person)
print(female_list)
# 2 변수로 저장할 필요가 있을 경우 이렇게 한다.
female_list_2 = [person for person in people if person["Sex"] == "Female"]
print(female_list_2)
# 3 변수로 저장할 필요가 없다면 바로 쓸 수도 있다.
print([person for person in people if person["Sex"] == "Female"])
- Map, Filter, lambda
people = [
{"Name": "Bob", "Sex": "Male", "Age": 15, "Height": 150},
{"Name": "Amy", "Sex": "Female", "Age": 18, "Height": 155},
{"Name": "Greg", "Sex": "Male", "Age": 16, "Height": 160},
{"Name": "Ray", "Sex": "Male", "Age": 22, "Height": 180},
{"Name": "Flora", "Sex": "Female", "Age": 24, "Height": 175},
{"Name": "Evan", "Sex": "Male", "Age": 30, "Height": 170}
]
# 함수 지정
def is_adult(person):
return "성인" if person["Age"] >= 18 else "청소년"
# 1 map(func, list)을 이용해 list의 모든 요소를 func의 return 값으로 구성된 리스트로 출력한다.
is_adult_list = list(map(is_adult, people))
print(adult_list)
# 2 변수로 저장할 필요가 있을 경우 이렇게 한다.
is_adult_list_2 = list(map(lambda x: ("성인" if x["Age"] >= 18 else "청소년"), people))
print(adult_list_2)
# 3 변수로 저장할 필요가 없다면 바로 쓸 수도 있다.
print(list(map(lambda x: ("성인" if x["Age"] >= 18 else "청소년"), people)))
people = [
{"Name": "Bob", "Sex": "Male", "Age": 15, "Height": 150},
{"Name": "Amy", "Sex": "Female", "Age": 18, "Height": 155},
{"Name": "Greg", "Sex": "Male", "Age": 16, "Height": 160},
{"Name": "Ray", "Sex": "Male", "Age": 22, "Height": 180},
{"Name": "Flora", "Sex": "Female", "Age": 24, "Height": 175},
{"Name": "Evan", "Sex": "Male", "Age": 30, "Height": 170}
]
# 함수 지정
def is_adult(person):
return True if person["Age"] >= 18 else False
# 1 filter(func(리턴이 bool), list)을 이용해 list의 요소 중 func의 return 값이 True인 리스트로 출력한다.
adult_list = list(filter(is_adult, people))
print(adult_list)
# 2 변수로 저장할 필요가 있을 경우 이렇게 한다.
adult_list_2 = list(filter(lambda x: x["Age"] >= 18, people))
print(adult_list_2)
# 3 변수로 저장할 필요가 없다면 바로 쓸 수도 있다.
print(list(filter(lambda x: x["Age"] >= 18, people)))
- 매개변수 (예시: connection 함수)
import time
# 연결할 DB 정보
info = {"SERVER": "xxx.xxx.xxx.xxx", "DATABASE": "Main", "UID": "Hello", "PWD": "World!"}
# DB connection 함수
# 기본 재시도 횟수: 5 (매개변수: retry_count)
def db_connection(retry_count=5):
for try_num in range(retry_count + 1):
try:
conn = connect(info)
cursor = conn.cursor()
except Exception as e:
print("[Error: DB Connection] ", e)
pass
else:
return cursor
if try_num == 5:
print("Connection will stop.")
return None
time.sleep(2 ** try_num)
print(f"RETRY CONNECTION... {try_num + 1}th try")
continue
- 매개변수(args, kwargs)
# 함수 input에 *을 지정하면 여러 input value를 args에 tuple 형태로 저장한다.
# *이 하는 역할이지, args의 역할이 아니다. (args 대신 다른 이름 사용 가능)
def greeting(*args):
print(f"args의 타입은 {type(args)} 입니다.")
for name in args:
print(f'{name}님 안녕하세요.')
# 함수 input에 **을 지정하면 여러 input value를 kwargs에 dictionary 형태로 저장한다.
# **이 하는 역할이지, kwargs의 역할이 아니다. (kwargs 대신 다른 이름 사용 가능)
# 매개변수로 어떤 것이 input 됐는지에 따라 function이 수행할 코드를 다르게 관리할 수 있다.
def greeting_kwargs(**kwargs):
print(f"kwargs의 타입은 {type(kwargs)} 입니다.")
for key, value in kwargs.items():
if key == "name":
print(f'{value}님 안녕하세요.')
if key == "age":
print(f"{'성인' if int(value) >= 18 else '청소년'}입니다.")
print(f"{key}: {value}")
greeting('철수', '영수', '희재')
greeting_kwargs(age='27')
greeting_kwargs(name='john', age='27')
'PYTHON' 카테고리의 다른 글
[TIL] 20240227 11일차 (1) | 2024.02.27 |
---|---|
[TIL] 20240226 10일차 (1) | 2024.02.26 |
[TIL] 20240223 9일차 (0) | 2024.02.23 |
[TIL] 20240222 8일차 (0) | 2024.02.22 |
[TIL] 20240221 7일차 (0) | 2024.02.21 |