함수.py

2023. 3. 11. 16:17·python
## 함수
def open_account():
    print("새 계좌가 생성되었습니다.")
# 함수호출해야지 작동함.

# balance : 잔액 / money : 입금할 금액
def deposit(balance, money):
    balance = balance+money
    print("입금이 완료되었습니다. 잔액은 {}원 입니다.".format(balance))
    plus = input("추가 입금하사겠습니까? : ")
    if plus == 'y':
        money = input("입금할 금액을 입력하세요 : ")
        balance = deposit(balance, int(money))
    return balance

# balance : 잔액 / money : 출금할 금액
def withdraw(balance, money):
    if balance >= money:
        balance = balance-money
        print("출금이 완료되었습니다. 잔액은 {}원 입니다.".format(balance))
        plus = input("추가 출금하사겠습니까? : ")
        if plus == 'y':
            money = input("출금할 금액을 입력하세요 : ")
            balance = withdraw(balance, int(money))
    else : 
        print("잔액이 {}원 부족합니다. 출금 금액을 확인해주세요".format(money - balance))

    return balance

# balance : 잔액 / money : 출금할 금액
def withdraw_night(balance, money):
    commission = 100 # 수수료
    if balance >= money+commission:
        balance = balance-money-commission
        print("출금이 완료되었습니다. 잔액은 {}원 입니다.".format(balance))
        plus = input("추가 출금하사겠습니까? : ")
        if plus == 'y':
            money = input("출금할 금액을 입력하세요 : ")
            balance = withdraw_night(balance, int(money))
    else : 
        print("잔액이 {}원 부족합니다. 출금 금액을 확인해주세요".format(money+commission - balance))
    # 여러개의 변수를 함꼐 반환할 수 있음.
    return balance, commission

open_account()
balance = 10000

money = input("입금할 금액을 입력하세요 : ")
balance = deposit(balance, int(money))
print("balance : ",balance)

money = input("출금할 금액을 입력하세요 : ")
balance = withdraw(balance, int(money))
print("balance : ",balance)

money = input("(밤)출금할 금액을 입력하세요 : ")
balance, commission = withdraw_night(balance, int(money))
print("balance, commission : ",balance, commission)
  • 함수는 def 함수명(변수, 변수, ...) : 으로 호출된다.
  • 재귀함수는 함수 안에 같은 함수를 호출하는 방식
    ㄴ return을 if문 안에 넣으니까 none값이 출력된다 (생각보다 구조가 헷갈린다.)
## 기본값
def profile(name, age, main_lang):
    print("이름 : {} \\t나이 : {}\\t사용언어 : {}"\\
          .format(name, age, main_lang))
    
profile("조OO", 29, "python")

# 함수명(변수, 변수 = 기본값) ... 을 사용할 수 있다.
# 다만 이 경우, 기본값이 있는 변수 뒤에는 무조건 기본값이 있어야 한다.
def default_profile(name, age=17, main_lang="파이썬"):
    print("이름 : {} \\t나이 : {}\\t사용언어 : {}"\\
          .format(name, age, main_lang))

default_profile("조OO")
default_profile("김OO")
  • 함수 변수값에 기본값을 입력하면 함수호출 시 입력하지 않아도 자동으로 값이 입력된다.
    ㄴ 다만 기본값이 있는 변수 뒤에 기본값이 없는 변수를 넣을순 없다.
## 키워드값
# 함수에서 받는 변수값을 키워드를 통해 입력 시, 순서에 관계없이 잘 전달됨
profile("조OO", main_lang = "Java", age= 24)
  • 함수 호출 시 “변수 = 값” 을 사용하여 순서 관계 없이 값을 전달할 수 있다.
## 가변인자
# 함수내 변수 앞에 *을 붙이면 넣고싶은만큼 값을 넣을 수 있다.
def changeable_profile(name, age, *lang):
    print("이름 : {} \\t나이 : {}\\t사용언어 : "\\
          .format(name, age),end = "")
    for i in lang:
        print("{}".format(i),end = ",")
    print()
    # print안에 반복문을 사용하고 싶다면 list화 해야함.
    print("{}".format([i for i in lang]))

changeable_profile("조OO", 29,"java", "c", "python", "selenium")
changeable_profile("김OO", 29,"html", "xlm")
  • 가변인자는 함수생성시 변수 앞에 *을 만들어 개수가 변경되는 값으로 전달할 수 있다.
    ㄴ 확인해보니 tuple 타입으로 전달되고 있다.(수정,삭제,입력 X 하지만 빠름)
## 지역변수와 전역변수
# 지역변수 : 함수 내에서만 사용할 수 있는 변수
# 전역변수 : 함수 외에서도 사용할 수 있는 변수

apple = 10

def remind_apple(eat):
    # 해당 케이스일 때, apple은 초기화되지 않아 에러 발생.
    # 즉 아래에 있는 apple은 지역변수
    # apple = apple - eat
    print ("함수 내 남은 사과 : {}".format(apple))

# 전역변수 : global 변수 = 값
def g_remind_apple(eat):
    # 전역공간에 있는 apple을 사용
    # 함수 내 연산이 전역변수에도 영향을 미침.
    global apple
    apple = apple - eat
    print ("함수 내 남은 사과 : {}".format(apple))

def return_remind_apple(apple, eat):
    apple -= eat
    print ("함수 내 남은 사과 : {}".format(apple))
    return apple

g_remind_apple(3)
print ("함수 밖 남은 사과 : {}".format(apple))
apple = return_remind_apple(apple, 2)
print ("함수 밖 남은 사과 : {}".format(apple))
  • 지역변수는 함수 내에서만 사용할 수 있는 변수로, 함수 안에서 호출됨
  • 전역변수는 함수 외에서도 사용할 수 있는 변수로, 함수 외에서 호출되며
    `global` 변수명 으로 함수 내에서 호출할 수 있다.
    ㄴ 다만 거의 대부분의 경우, 호출/return 으로 사용한다.
## 퀴즈
'''
표준 체중을 구하는 프로그램
1. 남자 : 키(m) x 키(m) x 22
2. 여자 : 키(m) x 키(m) x 21
-> 표준 체중은 소숫점 둘째자리까지 표시
'''

def std_weight(height, gender):
    print("키 {}cm {}의 표준 체중은, {} kg 입니다."\\
          .format(int(height*100), gender, \\
                  round(height*height*21 if gender == "여자" else height*height*22)))

std_weight(1.67 , "여자")

'python' 카테고리의 다른 글

클래스.py  (0) 2023.03.17
표준입출력.py  (0) 2023.03.14
분기.py  (0) 2023.03.11
자료구조.py  (0) 2023.03.11
문자열.py  (0) 2023.03.08
'python' 카테고리의 다른 글
  • 클래스.py
  • 표준입출력.py
  • 분기.py
  • 자료구조.py
몽자비루
몽자비루
코딩공부 정리용 블로그입니다.
  • 몽자비루
    공부하는 블로그
    몽자비루
  • 전체
    오늘
    어제
    • 분류 전체보기 (165)
      • python (30)
        • python_selenium (16)
        • python_pygame (3)
      • appium (0)
      • 쿠버네티스 (60)
        • linux (8)
        • shell programming (8)
        • docker (18)
        • cka (23)
      • postman&API (16)
      • QA성장하기 (30)
        • 개발자에서 아키텍트로 스터디 (6)
        • 소프트웨어 공학 이해도 높이기 (6)
        • 테스팅 전문 지식 쌓기 (18)
      • 에러일기 (1)
      • AWS (27)
      • Jmeter (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    공존성테스트
    cka
    테스트 계획서 만들어보기
    vi에디터
    linux
    qa
    k8s
    postman
    테스트 결과보고서
    포스트맨
    python
    로스트아크api
    .cpu
    네트워크 테스트
    테스트스크립트
    LOSTARK
    e2c
    리눅스
    스터디
    개발자에서아키텍트로
    쿠버네티스
    QAKOREA
    도커
    테스트 계획서
    로스트아크
    앱공존성
    API
    사드웨어리소스
    애플리케이션로그
    application log
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
몽자비루
함수.py
상단으로

티스토리툴바