Lecture 강의

Undergraduates 학부 Graduates 대학원 Lecture 역학 Lecture 설계 Lecture IT(IoT, AI) Lecture SAP2000 Lecture 아바쿠스 Lecture 파이썬 Lecture 엑셀 VBA Lecture 마이다스 Lecture 이탭스

[02. 문법] 2.4 함수 - def, return, 변수, 인자, dir, help

작성자 : kim2kie

(2023-02-19)

조회수 : 1071

[참조]

 

반복적인 작업을 함수로 만들어 재사용한다. 

(1) 내장함수(built-in function) 
(2) 함수의 정의: def
(3) (매개)변수와 인자
(4) 함수값 return
(5) mutable(변경 가능한) 인자 vs immutable(변경 불가능한) 인자
(6) opt를 사용한 default와 option 인자의 지정
(7) 인자의 개수가 정해지지 않을 때 사용하는 *arg와 **kwargs
(8) 함수 내 함수
(9) 사용자 정의 함수로 저장한 파일을 import로 불러오기
(10) 내포함수(內包함수; 內for함수; 
comprehension function)


 

(1) 내장함수(built-in function) 

  • 파이썬에 내장된 함수인 내장함수와 사용 예는 다음과 같다.
     
    abs()          : abs(3+4j)
    all()          : all([1,2,3]) vs. all([1,[],3])
    any()          : any([1,2,3]) vs. any([1,[],3])
    ascii()        : 
    bin()          : bin(2)
    bool()         : bool(a == 3)
    bytearray()    : 
    bytes()        : 
    callable()     : callable(a)
    chr()          : chr(97) ~ ord('a')
    classmethod()  : 
    compile()      : 
    complex()      : complex(1+2j)
    delattr()      : 
    dict()         : 
    dir()          : 모듈의 멤버 리스트; Ex) dir(max); max 모듈의 멤버 리스트
        
    함수 목록 출력
        모듈 안에 어떤 함수가 있는지 알아야 사용할 수가 있다.
        모듈 안에 함수 이름을 출력하는 방법으로 dir 함수를 사용한다. 

        예) math 모듈의 함수 목록을 출력해 보자
        
    >>> dir(math) 
    ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']


    divmod()       : divmod(5,3)
    enumerate()    : list(enumerate(['Spring', 'Summer', 'Fall', 'Winter']))
    eval()         : x = 1; eval('x+1')
    exec()         : 
    filter()       : list(filter(lambda x: x < 0, [-5,-3,0,3,5]))
    float()        : float(input('x = ? '))

    format() 함수      
        문자열을 포맷(즉, 서식 만들기)하는 데 사용되는 함수이다.
        문자열 내부에 {}과 같은 플레이스홀더(placeholder; 빠져 있는 다른 것을 대신하는 기호)를 사용하여 값을 삽입하고,
        format() 함수를 사용하여 플레이스홀더에 대응하는 값들을 전달한다.

        ex)
        >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
        'a, b, c'

        ex)
        >>> height = 175 # cm 단위
        >>> gender = "남자"
        >>> weight = 67.38
        >>> print("키 {0}cm {1}의 표준체중은 {2}kg 입니다.".format(height, gender, weight))

       키 175cm 남자의 표준체중은 67.38kg 입니다.


        대안 1) f-sring 
        대안 2) 문자열 연결
        대안 3) % 포맷팅


       

    frozenset()    : 
    getattr()      : 
    globals()      : globals()
    hasattr()      : 
    hash()         : 
    help()         : 도움말. Ex) help(max); max()에 대한 도움말

        함수 설명 출력
        어떤 함수 인지 알고 싶은 경우에는 help 함수를 사용한다. 

    >>> help(math.sin)
    Help on built-in function sin in module math:

    sin(x, /)
        Return the sine of x (measured in radians)


    hex()          : 
    id()           : a=3;b=a;   id(3); id(a); id(b)
    input()        : s = input('--> ')
    int()          : int('1')
    isinstance()   : class Person; a=Person(); isinstance(a,Person)
    issubclass()   : 
    iter()         : list(iter('formidable'))
    lambda         : sum = lambda a,b: a+b
    len()          : len([1,3,'a'])
    list()         : list('python') -> ['p', 'y', 't', 'h', 'o', 'n'] ~ 문자열 -> 리스트
    locals()       : locals()
    map()          : list(map(lambda x: x**2, [1,3,5]))
    max()          : max([1,3,5])
    memoryview()   : 
    min()          : min([1,3,5])
    next()         : x =iter([1,3,5]);next(x);...;next(x)
    object()       : 
    oct()          : 
    open()         : f = open('file.txt','w'); f.write(data); f.close();
    ord()          : ord('a') ~ chr(97)
    pow()          : pow(2,3)
    print()        : print(data)
    property()     : 
    range()        : range(start, stop, step)
       list(range(0,3)) 또는 range(0,3,1)
       ~정수(integer)로 범위를 나타낸다.
    repr()         : 
    reversed()     : 
    round()        : round(3.5)
    set()          : set([1,2,3])  -> {1, 2, 3} ~리스트 -> 집합. 
    setattr()      : 
    slice()        : 
    sorted()       : sorted([1,5,3,5])
    staticmethod() : 
    str()          : str(3) ~정수형 데이터 3을 문자 '3'으로 변환
    sum()          : sum([1,2,3])
    super()        : 
    tuple()        : tuple([1,2,3])
    type()         : type(3.5)
    vars()         : 
    zip()          : list(zip([1,2,3],[4,5,6]))
    __import__()   :

     

(2) 함수의 정의: def 

  • def func(...): 형태로 함수를 정의한다.
     
  • Ex)  
    def add(a,b):
        return a+b # a+b를 return한다.

    def printSomething(a,b,c):
        print(a,b,c) # return 없이 print만 한다.

    def printLogo(): # 인자(argument)가 없다.
        print('logo text')

    c=add(1,2)
    printSomething(1,2,3)
    printLogo()

     

(3) (매개)변수와 인자

  • (매개)변수(parameter; variable): 함수로 전달된 인자를 받아들이는 변수
  • 인자(argument): 어떤 함수를 호출시에 전달되는 값
     
  • Ex)
    def add_txt(t1, t2='파이썬'): # (매개)변수: t1, t2
        print(t1+" : "+t2)
        
    add_txt('hello','python') # 인자: 'hello', 'python'

     

(4) 함수값 return

  • 함수에서 계산된 함수값을 반환(return)한다.
     
  • Ex)
    def computeProps(n,p,q):
        a,b,c=n,p,q
        return (a,b,c) # 여러 값을 리턴할 때는 튜플로 리턴한다.

    r = computeProps(1,2,3) # 값을 받을 때는 한 개의 튜플로 받을 수도 있다.
    (a,b,c) = computeProps(1,2,3) # unpack(묶인 것을 푸는) 기능으로 낱개로 받을 수도 있다.
    a,b,c = computeProps(1,2,3) # 위와 동일

     

(5) mutable(변경 가능한) 인자 vs immutable(변경 불가능한) 인자

  • 인자로 mutable 자료형을 전달했을 때는 함수내에서 값이 바뀌는지 여부를 주의해야 한다.
  • 리턴값이 아닌 리턴 인자로 값을 받아오도록 설계할 수도 있다.
     

(6) opt를 사용한 default와 option 인자의 지정

  • def computeIgIcr(n,b,h,Ast,dt,Asc,dc,opt='exact'):
        n,b,h,n,b,h,Ast,dt,Asc,dc 

    Ig = computeIg(n,b,h,h,Ast,dt,Asc,dc)
    Ig = computeIg(n,b,h,h,Ast,dt,Asc,dc,’appr’)

     

(7) 인자의 개수가 정해지지 않을 때 사용하는 *arg와 **kwargs

  • Ex)
    def add(*args): # *args에서 *는 여러개의 인자를 튜플로 묶어 args (매개)변수로 함수에 전달하게 된다.
        r = 0
        for v in args:
          r = r + v
        return r

    r = add(1,2,3) # arg=(1,2,3) 형태로 전달되게 된다.
     

  • 일반 인자와도 같이 사용할 수 있는데 항상 뒤에 와야 한다. 
    def foo(x,*args) 형태이고, 
    foo(1,2,3,4,5)로 호출했다면 x=1, 
    args=(2,3,4,5)로 전달하는 식이다.

  • 비슷한 것으로 **kwargs가 있다. 이것은 keyword arguments로 이해할 수 있으며, 
    keyword1=value1, keyword2=value2, ... 형태를 dictionary로 만들어 준다.

     

  • Ex)
    def myfunc(**kwargs):
        print(kwargs)
        for key, value in kwargs.items():
            print(key,'=',value)

     

    myfunc(a=1,b=2,c=3)
     

  • Ex-Out)
    {'a': 1, 'b': 2, 'c': 3}
    a = 1
    b = 2
    c = 3

     

  • *args와 **kwargs는 일반 인자와 함께 사용될 수 있으며, 순서는 항상 다음과 같다.
     

  • Ex)
    def some_func(fargs,*args,**kwargs):
        pass

     

     

(8) 함수 내 함수

  • C/C++과 달리 함수내에서 함수를 정의해서 사용할 수 있다.
  • 자신을 둘러싼 함수의 변수를 마치 전역변수(global variable)처럼 사용할 수 있다.
     
  • Ex)
    def outside():
        outsideList = [1, 2]
        def nested():
            outsideList.append(3)
        nested()  # outside 함수 안의 구문이므로 줄을 띄어쓰지 않는다.
        print(outsideList)

    outside()
      

  • Ex-Out)
    [1, 2, 3]

 

(9) 사용자 정의 함수로 저장한 파일을 import로 불러오기

  • 김두기, 구조동역학, 2021: MATLAB/PYTHON: 1.4.6 진동가속도의 옥타브 대역 분석 (ch01_oct3, oct3dsgn)
  • "oct3dsgn.py"에서 정의한 함수 "oct3dsgn(Fc,Fs,N):"


    import numpy as np
    from scipy.signal import butter

    def oct3dsgn(Fc,Fs,N):   
        ...
        f2 = Fc*(2**(1/6)) 
        Qr = Fc/(f2-f1) 
        Qd = (np.pi/2/N)/(np.sin(np.pi/2/N))*Qr
        alpha = (1 + np.sqrt(1+4*Qd**2))/2/Qd 
        W1 = Fc/(Fs/2)/alpha
        W2 = Fc/(Fs/2)*alpha
        B,A = butter(N,[W1,W2],btype='bandpass')
        return B,A

  • "Ch01_4_oct3.py"에서 "oct3dsgn(Fc,Fs,N):" 함수를 불러오기
     

    import matplotlib.pyplot as plt
    import numpy as np
    from scipy.signal import lfilter

    import oct3dsgn as oc
    #
    xt = np.loadtxt('acc120km.dat')
    dt = 0.02;
    Fs = 1/dt;        # Sampling Frequency
    No = 3;           # Order of filters 
    FL =([[1.0, 1.25,  1.6],   
          [2.0,  2.5, 3.15],   
          [4.0,  5.0,  6.3],   
          [8.0, 10.0, 12.5]]);       # Preferred labeling freq. 
    FL = np.array([1.0, 1.25, 1.6, 2.0,  2.5, 3.15, # Preferred labeling freq.
                   4.0,  5.0, 6.3, 8.0, 10.0, 12.5]).reshape(-1, 1)  
    Fc = (1000./(2**(1/3))**np.arange(30,30-12,-1)).reshape(-1, 1)  # Exact center freq.
    RMSw = np.zeros((12, 1))
    ms = xt.shape[0] # No. of rows
    #
    # Implement filters to compute RMS in 1/3-oct. bands
    #
    for j in range(3,int(3-12/3),-1):
    #
        idxl = j*3    # idx to lower filter
        idxc = j*3+1  # idx to center filter
        idxu = j*3+2  # idx to upper filter
    #
        Bl,Al = oc.oct3dsgn(Fc[idxl],Fs,No) # lower 1/3-oct. band
        Bc,Ac = oc.oct3dsgn(Fc[idxc],Fs,No) # center 1/3-oct. band
        Bu,Au = oc.oct3dsgn(Fc[idxu],Fs,No) # upper 1/3-oct. band
    #
        y = lfilter(Bl,Al,xt,axis=0)
        RMSw[j*3  ] = np.sum(y**2, axis=0)/ms
        y = lfilter(Bc,Ac,xt,axis=0)
        RMSw[j*3+1] = np.sum(y**2, axis=0)/ms
        y = lfilter(Bu,Au,xt,axis=0)
        RMSw[j*3+2] = np.sum(y**2, axis=0)/ms 

 

(10) 내포함수(comprehension function)