Think of a piece of code as a black box
: can't see details
: don't need and don't want to see details
: hide tedious coding details
Achieve abstraction with function specifications of docstrings
Has name / parameters / docstring (optional but recommended) / body / returns something
Define Functions and Call
def is_even(i) :
# specification, docstring
"""
input : i, a positive int
Returns True if i is ever, otherwise False
"""
# body
print("inside is_even")
return i%2 == 0
is_even(3) # call function
return
: only has meaning inside a function
: only one return inside a function
: has a value associated with it, given to function caller
print
: can be used outside functions
: can execute many print stastements
: has a value associated with it, outputted to the console
: 앞으로 나올 scope에 대한 사진들은 python tutor 라는 홈페이지에서 프로그램을 돌려본 결과이다. 주소는 다음과 같다.
https://pythontutor.com/
def f(x) : # x is formal parameter
x = x+1
print('in f(X) : x =', x)
return x
x = 3
z = f(x) # x is actual parameter
Formal parameter
: the identifier used in a method to stand for the value that is passed into the method by a caller.
Actual parameter
: the actual value that is passed into the method by a caller.
New scope / frame / environment created when enter a function
말하자면 전역변수 / 지역변수의 개념인데, C에서 function에 따른 변수의 scope가 정의되는 것처럼 Python에서도 function에 따른 scope가 정의된다. 아래 그림을 보자.


def func_a() :
print('inside func_a')
def func_b(y) :
print('inside func_b')
return y
def func_c(z) :
print('inside func_c')
return z()
print(func_a())
print(5 + func_b(2))
print(func_c(func_a))
print(func_c(func_a)) 이전의 호출문은 쉬우니까 생략한다. 다음 그림을 보자.

func_c()를 호출, print('inside func_c') 를 수행한다. 이후, return 하기 전에 input으로 받은 func_a()를 실행한다.

func_a()는 None을 return한다. 이를 받아서 func_c가 return 한다. 이 return 한 값을 print한다.

def g(y) :
print(x)
print(x + 1)
# just using x
x = 5
g(x)
print(x)
# rusult is 5, 6, 5
# this code will make error
def h(y) :
x += 1 # UnboundLocalError
x = 5
h(x)
print(X)
def g(x) :
def h() :
x = 'abc'
x = x+1
print('g: x = ', x)
h()
return x
x = 3
z = g(x)
print(z)
Scope 의 관점에서 하나씩 살펴보자. global scope 에서 x = 3, g scope 에서 x = 3을 받는다.

g 함수 내에서 정의된 h함수는 g scope 내에서 h scope를 만들고, 그 함수는 x = 'abc'라는 명령을 수행하도록 정의되었다. x는 x = x+1에 의해 3에서 1 증가한 4가 된다.

h() 를 수행한다. h scope 내에서 x는 'abc'로 재정의되지만, g scope에는 영향을 미치지 않는다. 그 결과 g는 x = 4 를 return한다.

그 결과 z는 4를 받는다. print(z)의 결과는 4를 출력한다.
