Python - 조건문(if)과 함수인자(argument)

jinatra·2021년 8월 6일
1

Python

목록 보기
2/15
post-thumbnail

Python - 조건문(if)과 함수인수(argument)


If문 들여쓰기(indents)

if문의 expression 이 True 일때 실행되야 하는 코드들은 항상 if문 보다 시작 간격이 더 안으로 들어와 있어야한다
if문과 동일 간격 선상에 있는 구문은 if문과 관계 없는 독립적인 구문으로 취급

condition1 = 23

if condition1 == 23:
    print('이건 if가 참일때 출력되는거에요!!')
print('이건 들여쓰기 안된거니까 if문에 관계없이 무조건 출력!!')


# Output
이건 if가 참일때 출력되는거에요!!
이건 들여쓰기 안된거니까 if문에 관계없이 무조건 출력!!

Data Type 반환

큰 따옴표("")와 작은 따옴표('')가 붙어있지 않은 True, False는 boolean 값이다.
항상 명심하자.

def quiz(world):
    if world == 'real':
        return(True)
    if world != 'real':
        return(False)

print(quiz('real'))


# Output
True #string이 아닌 boolean값

Comments

# : 한줄 코멘트
''' ''' : 여러줄 코멘트

그러나 여러줄 코멘트를 쓸 때 줄마다 #을 사용하는게 일반적

# 나는 한줄 코멘트!

'''
나는 여러줄 코멘트!
'''

# 하지만 다수의 코멘트를 출력할때에도
# 이렇게 #을 이용해서 하는데
# 이 방법이 더 일반적

Returns

return

함수 내에서 정의된 값을 함수 바깥으로 반환

current_budget = 3500.75

def print_remaining_budget(budget):
  print("Your remaining budget is: $" + str(budget))

print_remaining_budget(current_budget)

# (budget - expense) 값을 함수 deduct_expense의 반환값으로 지정
def deduct_expense(budget, expense):
  return budget - expense

shirt_expense = 9

# new_budget_after_shirt = (current_budget - shirt_expense)
new_budget_after_shirt = deduct_expense(current_budget, shirt_expense)

print_remaining_budget(new_budget_after_shirt)

# Output:  Your remaining budget is: $3500.75
# Output:  Your remaining budget is: $3491.75

Types of Arguments

  • Positional arguments (위치 인수) → 함수에서 정의한 위치에 대입되는 인수
  • Keyword arguments (키워드 인수) → 순서 필요 없이 기입된 값을 함수에 전달하는 인수
  • Default arguments (기본 인수) → 기본값이 설정되는 인수
# Positional arguments

def player_of_the_match(name):
    print('Player of the match is... ' + name + '!')

player_of_the_match('Tierny')

# Output: Player of the match is... Tierny!
# 지정된 parameter에 지정된 argument 출력
# Keyword arguments

def ticket_price(price, person, discount):
    print(price * person - discount)

ticket_price(person = 5, discount = 30, price = 20)

# Output: 70
# parameter 순서에 상관없이 argument 지정
# Default arguments

def ticket_price(price, person, discount = 10):
    print(price * person - discount)

ticket_price(20, 5)

ticket_price(20, 5, 20)

# Output: 90
# default argument 생략 가능

# Output: 80
# 때에 따라 default argument에 새로운 값을 덮어씌울 수 있다



Take Away

return의 필수성

return이 반드시 fucntion안에 들어가야하는 것은 아니지만, 함수의 근본적인 목적은 입력을 통한 출력이기에 출력값을 외부에 반환시키기 위해서는 return이 필요하다.
return값이 지정되지 않은 함수는 외부에 none으로 출력된다고 한다.

profile
으악

1개의 댓글

comment-user-thumbnail
2021년 8월 6일

👍

답글 달기