U E D R , A S I H C RSS

2학기파이선스터디/함수


1.

~cpp 
def 명(들..):
    문들(statements)
    return <값>


~cpp 
def add(a,b):
    return a+b

return 된 값 로 돌려다. def는 고 그 객
add란 다. , add는 reference를 갖고 다.

add는 므로 다른 다.
~cpp 
>>> f = add
>>> f(4,5)
9

pass는 과문(statement)다. 기 때문 다.
~cpp 
def add(a,b):
    pass

2. 달 방법

~cpp 
>>> def f(t):
	t = 10

	
>>> a = 20      # a는 객 20 다.
>>> f(a)        # a를 t를  므로 t는 a 를 갖는다. 그리고 t = 10 t가 객 10 다. 때 a 는 변다.
>>> print a
20

3. return문

~cpp 
>>> def f():
	return

>>> f()
>>> a = f()
>>> print a
None
return문 만 무 값 는다.
return 만, 로는 None 객달된다.
None 객, 무 값 내기 다.

달되 다면 a가 다.

return문 None라는 리 다.
, 리 나 None 객긴다.

4. Scoping Rule

*
  • (local scope) -
  • (global scope) - 모()
  • (built-in scope) -

LGB 따른다.
LGB는 Local, Global, Built-in , , 내 된다.

~cpp 
# g, h는  
g = 10
h = 5

def f(a):       # a는 
    h = a + 10  # h는 (므로)
    b = a + g   # b , g는 
    return b

g, h는 므로 , a,b는 내부되는 다.
h는 내부 므로 내부 h를,
h를 다.
f f가 료되면 다( 다).


f내부 h를 려면(, h 바꾸고다면)
global문 h가 다.
~cpp 
def f(a):       # a는 
    global h
    h = a + 10  # h는 

~cpp 
g = 10

def f():
    a = g
    g = 20
    return a

f()

  • (Nested scopes) (2.1)

~cpp 
x = 2           # global
def F():
    x = 1       #  G  기는 local global 다
    def G():
        print x
    G()

F()
G 는 x는 ( G), (모), 내 게 되므로 F 된 x가 는다.(x = 2)
그러나 2.1 F x를 므로 바른 결과가 나다.

5.1. 기본

~cpp 
>>> def incr(a, step=1):
	return a + step

>>> b = 1
>>> b = incr(b)        # 1 가
>>> b
2
>>> b = incr(b, 10)    # 10 가
>>> b
12

5.2.

~cpp 
>>> def area(height, width):
	print height, width
	# 로 값 달된다

	
>>> a = area(width=20, height=10)
10 20

5.3. 가변

달 - 나머는 모두 는다
~cpp 
>>> def varg(a, *arg):
	print a, arg
	
>>> varg(1)
1 ()
>>> varg(2,3)
2 (3,)
>>> varg(2,3,4,5,6)
2 (3, 4, 5, 6)

5.4.

미리 려면 **kw로 기다.
다. 드(변명), 값 달된 값 된다.
~cpp 
>>> def f(width, height, **kw):
	print width, height
	print kw

	
>>> f(width = 10, height=5, depth=10, dimension=3)
10 5
{'depth': 10, 'dimension': 3}

5.5. 기(2.0 )

~cpp 
>>> def h(a,b,c):
	print a,b,c

	
>>> args = (1,2,3)
>>> h(*args)
1 2 3
~cpp 
>>> dargs = {'a':1, 'b':2, 'c':3}
>>> h(**dargs)
1 2 3
~cpp 
>>> args = (1,2)
>>> dargs ={'c':3}
>>> h(*args, **dargs)
1 2 3

6. 람다

람다 다.
~cpp 
lambda 로 구들: 
~cpp 
>>> f = lambda:1
>>> f()
1
~cpp 
>>> g = lambda x, y: x+y
>>> g(1,2)
3
~cpp 
>>> incr = lambda x, inc=1: x+inc
>>> incr(10)
11
>>> incr(10,5)
15
~cpp 
>>> vargs = lambda x, *args: args
>>> vargs(1,2,3,4,5)
(2, 3, 4, 5)
~cpp 
>>> kwords = lambda x, *args, **kw: kw
>>> kwords(1,2,3, a=4, b=6)
{'a': 4, 'b': 6}
def로 되는 lambda
문/ 문(statement) (expression)
def 다
return문 로 리 된다 결과가 리된다
내부 변 는 것 가능 는 것 가능

7. 로그래밍

~cpp 
>>> def sum(N):
	if N==1: return 1
	return N + sum(N-1)

>>> sum(10)
55
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:22:13
Processing time 0.0208 sec