python3 기초2 - funtions

Defining Functions

반복되는 statement들을 줄이고 프로그램을 잘게 쪼개어 유지관리가 용이하도록 function를 활용한다.

함수를 정의한 다음에는 두줄을 띄운다.

함수이름은 문자 또는 ‘_’으로 시작하고 소문자를 쓴다.

def hello():
    print("hi")
    print("welcome")

hello()


Arguments

  • Parameters : 함수 정의할 때 쓰는 변수
  • Arguments : 함수를 호출할때 입력하는 값

Default로 parameter는 정의한 수 만큼 required이다. 함수 정의할때 parameter를 두개 정의했으면 함수를 쓸 때 argument는 두개를 필수로 전달해야한다

def hello(first_name, last_name):
    print(f"hi {first_name} {last_name}")
    print("welcome")

hello("Jihoon", "Kang")


Types of Functions

함수는 두 종류가 있다

  • Task를 실행하는 함수
  • 값을 반환하는 함수
def hello(name):
    print(f"Hi {name}")

def get_hello(name):
    return f"HI {name}"

message = get_hello("jihoon")
print(message)

Task를 실행하는 함수는 정의된 task만 실행하지만 값을 반환하는 함수는 그 값을 변수로 저장하거나 다른 함수에 argument로 활용할 수 있다는 장점이 있다.

Task를 실행하는 함수를 print하면 항상 None이 출력된다.

Funtion은 return값을 정의하지 않으면 기본적으로 항상 None을 출력한다.

def hello(name):
    print(f"Hi {name}")

print(hello("jihoon"))     

## Hi jihoon
## None


Key word Arguments

argument가 여러 개 일때, parameter를 같이 명시해주면 알아보기 편하다

def increment(number, by):
    return number + by

print(increment(2, by=1))


Default Arguments

  • function을 정의할 때 parameter에 값을 정의해주면 해당 parameter는 optional이 된다.
  • optional parameter는 function을 호출할때 argument를 입력하지 않으면 기본값이 적용된다.
  • optional parameter는 function 정의시 항상 required parameter 보다 뒤에 명시되어야 한다.
def increment(number, by=1):
    return number + by

print(increment(2))


*args

  • parameter 앞에 *을 붙이면 복수의 argument를 입력할 수 있다.
  • 복수의 argument 결과는 tuple이다.
  • tuple는 list와 달리 수정할 수 없다.
def multiply(*numbers):
    print(numbers)

print(multiply(2, 4, 5, 6))

## (2, 4, 5, 6)
## None
  • tuple은 list와 마찬가지로 iterable 하다.
def multiply(*numbers):
    total = 1
    for number in numbers:
        total *= number
    return total

print(multiply(2, 4, 5, 6))

## 240


**args

  • parameter 앞에 **를 붙이면 keyword argument를 입력할 수 있다.
  • 결과는 dictionary로 저장된다
def save_user(**user):
    print(user)

save_user(id=1, name="John", age=22)

## {'id': 1, 'name': 'John', 'age': 22}
  • 특정 key를 반환할 수도 있다.
def save_user(**user):
    print(user["name"])

save_user(id=1, name="John", age=22)

## John


Scope

  • 함수에서 정의한 parameter 명과 변수는 local 변수이다.
  • local 변수는 자신이 속한 함수가 실행될때만 메모리에 저장되고 함수 실행이 끝나면 더이상 메모리에 저장되지 않는다.
  • 다른 함수에서 같은 이름의 parameter나 변수이름을 써도 서로 영향을 미치지 않는다.
def greet(name):
		message = "a"

def send_mail(name):
		message = "b"
  • global 변수는 오랫동안 저장된다. → local 변수나 parameter를 가능한 활용하는게 좋다.
  • global 변수와 local 변수 이름이 같다고 하더라도 local 변수는 함수 실행동안에만 저장되므로 아래 예처럼 작성해도 global 변수 값을 변경할 수 없다.
message = "a"

def greet(name):
    message = "b"

greet("John")
print(message)

## a
  • global message 를 쓰면 global 변수 message를 수정할 수 있다.
  • 하지만 여러 함수를 정의하고 global 변수에 영향을 미치는 많은 함수들이 있는 경우 프로그램 유지보수에 좋지 않으므로 global 변수를 함수에서 변경하는 것은 절대 피하도록한다.

댓글 쓰기

0 댓글