Python MIT OCW Lec4 : Decomposition, Abstraction, Functions

김재만·2023년 9월 18일

Python MIT OCW

목록 보기
4/9

배울 내용

  1. Structuring programs and hiding detais
  2. Functions
  3. Specifications
  4. Keywords : return vs print
  5. Scope

1. Structuring Programs and Hiding Details

Good Programming

  • Measure good programmers by the amount of functionality
  • introduce functions
  • mechanism to achieve decomposition and abstraction

Create structures with decomposition

  • Divide code into modules
    : self-contained
    : used to break up code
    : reusable
    : keep code organized and coherent(일관성 있는)
  • Achieve decomposition with functions and classes

Supress Details with abstraction

  • 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

2. Functions

  • 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
  • def : keyword
  • is_even : name
  • i : parameters or arguments

If no return statement in function definition

  • Python returns the value None, if no return given
    : not a string, but special type
  • represent the absence of a value

return vs. print

  • 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

3. Variable Scope

: 앞으로 나올 scope에 대한 사진들은 python tutor 라는 홈페이지에서 프로그램을 돌려본 결과이다. 주소는 다음과 같다.
https://pythontutor.com/

  • See this code :
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가 정의된다. 아래 그림을 보자.

  • f frame에서의 return 하는 x 값은 4. 이는 global frame에서의 x 값과는 무관하다.

  • f frame에서 return 한 값은 global frame 에서 z가 받는다.

Functions as arguments

  • See this code
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한다.

Scope Example

  • inside a funciton, can access a variable defined outside
def g(y) : 
  print(x)
  print(x + 1)
  # just using x

x = 5
g(x)
print(x)

# rusult is 5, 6, 5
  • inside a function, cannot modify a variable defined outside, can using global variables, but frowned upon
# this code will make error

def h(y) : 
  x += 1 # UnboundLocalError

x = 5
h(x)
print(X)

Scope details

  • See this code
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를 출력한다.

profile
Hardware Engineer가 되자

0개의 댓글