본문 바로가기

Backend/Python

함수

전달값과 반환값

# 계좌 개설
def open_account():
    print("새로운 계좌가 생성되었습니다.")
# 입금
def deposit(balance, money):
    print("입금이 완료되었습니다. 잔액은 {0}원입니다.".format(balance+money))
    return balance+money
# 출금
def withdraw(balance, money):
    if balance >= money:
        print("출금이 완료되었습니다. 잔액은 {0}원입니다.".format(balance-money))
        return balance - money
    else:
        print("출금이 완료되지 않았습니다. 잔액은 {0}원입니다.".format(balance))
        return balance
# 수수료
def withdraw_night(balance, money):
    commision = 100  # 수수료 100원
    return commision, balance - money - commision

balance = 0  # 처음 잔액
balance = deposit(balance, 1000) #입금
balance = withdraw(balance, 2000) #출금
balance = withdraw(balance, 200)
commision, balance = withdraw_night(balance, 500)
print("수수료 {0}원이며, 잔액은 {1}원입니다.".format(commision, balance))

가변인자(*)

 def profile(name, age, lang1, lang2, lang3, lang4, lang5):
     print("이름:{0}\t나이:{1}\t".format(name, age), end=" ") # end=" "는 줄바꿈
     print(lang1, lang2, lang3, lang4, lang5)

def profile(name, age, *language):
    print("이름:{0}\t나이:{1}\t".format(name, age), end=" ")
    for lang in language:
        print(lang, end=" ")
    print()

profile("유재석", 20, "Python", "Java", "C", "C++", "C#", "Javascript")
profile("김태호", 25, "Kotlin", "Swift")

퀴즈 

# 표준 체중을 구하는 프로그램을 작성하시오
# 남자 : 키(m) X 키(m) X 22
# 여자 : 키(m) X 키(m) X 21
# 별도의 함수(std_weight) 내에서 계산
# 전달값 : 키(height), 성별(gender)
# 표준 체중은 소수점 둘째자리까지 표시
# (출력예제)
# 키 175cm 남자의 표준 체중은 67.38kg입니다.

def std_weight(height, gender):
    if gender == "남자":
        return height * height * 22
    else:
        return height * height * 21
        
height = 175(cm)
gender = "남자"
weight = round(std_weight(height / 100, gender), 2)
print("키 {0}cm {1}의 표준 체중은 {2}kg 입니다.".format(height, gender, weight))

'Backend > Python' 카테고리의 다른 글

클래스  (0) 2022.02.05
입출력  (0) 2022.02.01
제어문  (0) 2022.02.01
자료구조  (0) 2022.01.31
문자열 처리  (0) 2022.01.29