1. enumerate()
for 변수in enumerate([list요소들]):
print(변수)
인덱스와 원소로 이루어진 튜플을 만들어준다.
인덱스와 원소를 각각 다른 변수에 할당하고 싶으면 인자풀기(unpacking)해주면 된다
2. 고객관리시스템 함수로 간결하게 표현하기
저번에 간결하게 정리할때 input 함수 안에서도 또 다른 함수를 사용하여 더 간결하게 만들 수 있지 않을까 하는 생각을하고 시도해보았는데 실패했다
이를 강사님과 함께 정리해보았다
chk_input_data() 에 네가지의 정보를 입력받고 조건에 충족하는 정보가 입력될때까지 while문이 반복되는 구조를 작성하였다.
이때 정말 간결하다고 생각했던 점은 def chk_name()과 같이 조건문을 각기 다른 함수명을 가진 함수들을 생성할 필요가 없이 lambda를 사용하여 한 줄로 조건을 준 것이다.
def customer_input(customers):
print('고객 정보 입력')
customer = {'name':'', 'gender':'','email':'','year':0} # 또는 customer = dict()
# def chk_name(x):
# if len(x)>2:
# return True
# else:
# return False
# 위와 같은 함수를 지정하지 않고 lambda를 사용하면 훨씬 간결하게 사용할 수 있다(함수명 지정할 필요 없음)
customer['name'] = chk_input_data('이름을 입력하세요 : ', lambda x:True if len(x)>2 else False )
customer['gender'] = chk_input_data('성별 (M/F)를 입력하세요. :', lambda x:True if x in ('M','F') else False)
customer['email'] = chk_input_data('이메일 주소를 입력하세요. :', lambda x:True if '@'in x else False)
customer['year'] = chk_input_data('출생년도 4자리를 입력하세요. :', lambda x: True if len(x)==4 and x.isdigit() else False)
print(customer)
customers.append(customer)
print(customers)
#사용자로부터 데이터를 입력받고 입력받는 데이터를 검토한다
#첫번째 파라미터는 로직(함수)이여야한다
#두번째 파라미터는 인풋에 사용되는 메세지 문자열
def chk_input_data(msg,func):
while True:
x = input(msg).upper()
if func(x):
break
else:
print('잘못 입력하셨습니다. 다시 입력 해주세요. :')
return x
3. 함수를 모듈로 저장하여 불러와서 사용하기
고객관리시스템의 함수들을 모듈로 저장하여 불러와서 사용하는 실습을 해봤다.
위와 같이 함수들을 모듈로 정리하여 저장하였다
알아보기 쉽게 함수의 이름과 동일한 파일명을 사용하였는데 굳이 그렇게는 안해도 될 것 같다
from cust.delete.customer_delete import customer_delete
from cust.insert.customer_input import customer_input
from cust.read.customer_search_c import customer_search_c
from cust.read.customer_search_n import customer_search_n
from cust.read.customer_search_p import customer_search_p
from cust.update.customer_update import customer_update
def main():
customers = list() #위치 중요..!
index = -1
while True:
menu = input('''
다음 중에서 하실 작업의 메뉴를 입력하세요.
I - 고객 정보 입력
P - 이전 고객 정보 조회
C - 현재 고객 정보 조회
N - 다음 고객 정보 조회
U - 현재 고객 정보 수정
D - 현재 고객 정보 삭제
Q - 프로그램 종료
''')
if menu.upper() == 'I':
index = customer_input(customers,index)
print('index:',index)
print('customers:',customers)
elif menu.upper() == 'P':
index = customer_search_p(index,customers)
print('index:',index)
elif menu.upper() == 'C':
customer_search_c(index,customers)
elif menu.upper() == 'N':
index = customer_search_n(index,customers)
print('index:',index)
elif menu.upper() == 'U': #loop문? 이용해서 고객 찾아서 정보 수정하는것도 해봐..
customer_update(index,customers)
elif menu.upper() == 'D':
customer_delete(index,customers)
elif menu.upper() == 'Q':
print('안녕히가세요.')
break
else:
print('잘못 입력하셨습니다. 다시 입력해주세요.')
그 뒤 다음과 같이 from 파일경로.파일명 import 함수명 으로 import를 한 뒤 함수를 그대로 main에서 사용하였다.
이때 추가적으로 main()의 바깥에서 선언되었던 customers와 index를 while 안으로 위치를 변경하였다
따라서 각각의 함수를 사용할때 파라미터로 customers를 넣어주었더니 잘 작동하는 것을 확인할 수 있었다
+ index 값을 return으로 보내서 main에서 다시 index값을 저장해주어야 이전 이후 데이터 조회시에 제대로 작동한다
'Python' 카테고리의 다른 글
Python 매개변수, 데코레이터(Decorator) (6) | 2023.11.14 |
---|---|
Python 유니코드, 클로저 (5) | 2023.11.14 |
List 내 for 문 (0) | 2023.11.07 |
Python 고객관리시스템(함수로 메인 로직 간결하게) (1) | 2023.11.07 |
Python 함수 (0) | 2023.11.07 |