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.0219 sec