디폴트매개변수
: 인자값이 없더라도 매개변수에 기본 지정값을 통하여 초기화를 해주는 기능
함수의 수를 줄이고 통합적인 처리를 하기위해서 만들어진 문법이다
매개변수에 대입연산자를 통해 기본값으로 지정하면 된다
디폴트 매개변수 사용 시 주의사항
인자값을 적은 순서대로 매개변수 왼쪽부터 차례로 들어간다
디폴트 매개변수를 정의할 때는 반드시 가장 우측부터 정의하여야 한다
def disp(a,b=10,c=30):
print(a,b,c)
disp(1)
disp(1,2)
disp(1,2,3)
출력화면
키워드인자
: 매개변수에 들어갈 데이터를 지정하여 넣는 문법
필요에 따라 매개변수를 지정하여 데이터를 넣어줄수 있는 문법
호출할때 매개변수명=인자값
disp(5,c=20) # 매개변수 지정 없는 값은 a의 값이 된다 ; a의 값은 필수이므로 반드시 필요
disp(b=20,a=10)
출력화면
디폴트 매개변수를 이용한 함수
add() 함수
: 전달한 매개변수 범위의 합계를 구한다
디폴트 매개변수를 이용하여 Add() 함수 만들기
인수를 전달받지 않으면, 디폴트 값인 1~100 사이의 합을 리턴한다
인수를 한 개 전달받으면, x~100 사이의 합을 리턴한다
인수를 두 개 전달받으면, x~y 사이의 합을 리턴한다
def add(x:int=1,y=100):
tot = 0
for i in range(x,y + 1):
tot+=i
return tot
print(add()) # 기본값인 1부터 100까지 합을 구함
print(add(12)) # x에 12를 전달하고 y는 기본값인 100을 사용해 12부터 100까지의 합을 구함
print(add(50)) # x에 50을 전달하고 y는 기본값인 100을 사용해 50부터 100까지의 합을 구함
print(add(y = 15)) # y에 15를 전달하고 x는 기본값인 1을 사용해 1부터 15까지의 합을 구함
print(add(1,10))
출력화면
printChar() 함수
: 전달받은 문자를 개수만큼 출력하는 함수
첫번째 매개변수에는 문자, 두번째 매개변수에는 개수를 전달한다
인수를 전달받지 않으면, 디폴트 값인 문자 '*'를 10개 출력한다
인수를 한 개 전달받으면, 전달받은 문자를 10개 출력한다
인수를 두 개 전달받으면, 전달받은 문자를 전달받은 개수만큼 출력한다
def printChar(ch='*',n=10):
print(ch*n)
printChar()
printChar("-")
printChar("$",20)
출력화면
outDate() 함수
: 년, 월, 일을 전달받아 출력
년, 월, 일, 날짜구분기호를 전달받아 출력
2004/3/5
2007#8#5
2006/9/2
def outDate(y,m,d,ch="/"):
print(y,m,d,sep=ch)
outDate(2004,3,5)
outDate(2007,8,5,"#")
outDate(2007,8,5,"-")
출력화면
가변인자
: 매개변수의 개수를 상황에 따라서 여러 개 둘 수 있는 매개변수
매개변수 앞에 *을 붙여서 선언하면 된다
가변 인자를 통해서 데이터를 받으면 매개변수의 타입은 튜플이 된다
def tot(a,*data) -> int:
print(data)
print(type(data))
t = 0
for i in data:
t += i
return t
tot(1,2,3,4,5,6,7,8,9,0)
출력화면
1은 매개변수 a에 전달되고 그 이후부터 출력
def disp(*data,sep=" ",end="\n") -> None:
msg = ""
for i in range(data.__len__()):
msg += str(data[i])
if i != data.__len__() - 1:
msg+=sep
msg+=end
print(msg)
disp(1,2,3,4,5,6,7,8,sep="-",end="asdf")
출력화면
키워드 가변인자
: 키워드를 지정하여 인자값을 넣는데 인자값에 변수명을 지정하여 넣는 방식
매개변수 앞에 **를 적어주면 된다
키워드 가변인자는 딕셔너리 타입이다
def disp(**data):
print(data)
print(type(data))
disp(a = 1,b = 2)
출력화면
Exercise1
학생부 프로그램
학생의 인적 사항 등록 후 검색, 수정, 삭제
학번 , 이름 , 주소
{학번 : { 이름 : 데이터 , 주소 : 데이터 }}
1. 인적사항 등록
2. 검색 : 1.학번(같을 경우 출력) 2.이름(포함검색) 3.주소(포함검색)
3. 수정
4. 삭제
5. 전체 보기
6. 종료
from datetime import datetime
import os
while True:
def msgInput(msg):
return input("{} 입력 : ".format(msg))
def createNo(su):
now = datetime.now()
return "{}{:02}{:04}".format(now.year,now.month,su + 1)
def createInfo(info:dict):
name = msgInput("이름")
addr = msgInput("주소")
no = createNo(info.__len__())
info.setdefault(no,{"name" : name , "addr" : addr})
print("{}님의 정보가 추가되었습니다".format(name))
def selectNo(info:dict):
no = msgInput("검색할 학번")
if info.get(no) != None:
print("학번\t\t이름\t주소")
print("{}\t{}\t{}".format(no,info[no]["name"],info[no]["addr"]))
else:
print("검색할 학번이 없습니다.")
def selectTest(info:dict,mode:str):
tp = ("이름","주소")
if mode == "name":
i = 0
else :
i = 1
select = msgInput("검색할 {}".format(tp[i]))
# if mode == "name":
# select = msgInput("검색할 이름")
# else:
# select = msgInput("검색할 주소")
check = True
for no,v in info.items():
if v.get(mode).find(select) != -1:
print("{}\t{}\t{}".format(no,v["name"],v["addr"]))
check = False
if check:
print("{}이 검색되지 않습니다.".format(tp[i]))
# if check:
# if mode == "name":
# print("이름이 검색되지 않습니다.")
# else:
# print("주소가 검색되지 않습니다.")
def selectName(info:dict):
name = msgInput("검색할 이름")
check = True
for no,v in info.items():
if v.get("name").find(name) != -1:
print("{}\t{}\t{}".format(no,v["name"],v["addr"]))
check = False
if check:
print("이름이 검색되지 않습니다.")
def selectAddr(info:dict):
addr = msgInput("검색할 주소")
check = True
for no,v in info.items():
if v.get("addr").find(addr) != -1:
print("{}\t{}\t{}".format(no,v["name"],v["addr"]))
check = False
if check:
print("주소가 검색되지 않습니다.")
def selectInfo(info:dict):
select = int(input("1.학번검색\n2.이름검색\n3.주소검색\n입력 : "))
if select == 1:
selectNo(info)
elif select == 2:
selectName(info)
elif select == 3:
selectAddr(info)
else:
print("잘못된 선택!")
def updateInfo(info:dict):
no = msgInput("수정할 학번")
if info.get(no) != None:
st = info.get(no)
print("학번\t\t이름\t주소")
print("{}\t{}\t{}".format(no,st.get("name"),st.get("addr")))
name = input("수정할 이름 입력 : ")
addr = input("수정할 주소 입력 : ")
st["name"] = name
st["addr"] = addr
print("{}의 정보가 수정되었습니다.".format(no))
else:
print("학번이 잘못입력되었습니다.")
def deleteInfo(info:dict):
no = msgInput("삭제할 학번")
if info.get(no) != None:
print("{}님의 정보가 삭제되었습니다".format(info.pop(no).get("name")))
else:
print("학번이 잘못입력되었습니다.")
def disp(info:dict):
if info.__len__() == 0:
print("데이터가 없습니다.")
else:
for no in info:
print("학번 : {}".format(no),end="\t")
for key in info[no]:
print("{} : {}".format(key,info[no][key]),end="\t")
print()
def menu():
info = {}
while True:
select = int(input("1. 인적사항 등록\n2. 검색\n3. 수정\n4. 삭제\n5. 전체 보기\n6. 종료\n입력 : "))
if select == 1:
createInfo(info)
elif select == 2:
selectInfo(info)
elif select == 3:
updateInfo(info)
elif select == 4:
deleteInfo(info)
elif select == 5:
disp(info)
elif select == 6:
print("프로그램이 종료됩니다.")
exit()
else :
print("잘못된 메뉴 입력!")
os.system("pause")
os.system("cls")
menu()
출력화면
Exercise2
리터널상수 , 심볼릭상수.... X
심볼릭상수를 인위적으로 표현한다
변수명을 대문자로 작성하여 상수를 표현하기도 한다
IN = True
OUT = False
def setRooms() -> list:
su = int(input("방 개수 입력 : "))
return initRooms(su)
def initRooms(su):
rooms = []
for i in range(su):
rooms.append(OUT)
return rooms
def esc():
print("프로그램이 종료됩니다.")
exit()
def disp(rooms:list):
print("### 현황 ###")
for i in range(rooms.__len__()):
if rooms[i]:
print("{}호실 - 입실중".format(i + 1))
else:
print("{}호실 - 빈방".format(i + 1))
def roomInput(msg:str,su:int):
while True:
room = int(input("{}하실 방 번호 입력 : ".format(msg)))
if room >= 1 and room <= su:
return room
else:
print("방번호는 1호실부터 {}호실까지 있습니다.".format(su))
def checkIn(rooms:list):
room = roomInput("입실",rooms.__len__())
if rooms[room - 1]:
print("{}호실은 현재 사용중인 방입니다.".format(room))
else:
rooms[room - 1] = IN
print("{}호실에 입실하셨습니다.".format(room))
def checkOut(rooms:list):
room = roomInput("퇴실",rooms.__len__())
if not rooms[room - 1]:
print("{}호실은 빈 방입니다.".format(room))
else:
rooms[room - 1] = OUT
print("{}호실에 퇴실하셨습니다.".format(room))
def menu():
rooms = setRooms()
while True:
select = int(input("1.입실 2.퇴실 3.보기 4.종료 : "))
if select == 1:
checkIn(rooms)
elif select == 2:
checkOut(rooms)
elif select == 3:
disp(rooms)
elif select == 4:
esc()
else:
print("잘못된 메뉴 입력!")
menu()
출력화면
'Backend > Python' 카테고리의 다른 글
Python 파이썬 생성자 객체 생성 순서 (0) | 2023.07.04 |
---|---|
Python 파이썬 객체지향 프로그래밍 (0) | 2023.07.03 |
Python 파이썬 Dictionary 함수 및 예제 (0) | 2023.07.03 |
Python 파이썬 함수 (0) | 2023.07.03 |
Python 파이썬 리스트 : 리스트 관련 함수 및 예제 (0) | 2023.07.03 |