오류 처리 소개

Python 함수 입문

Hugo Bowne-Anderson

Instructor

float() 함수

2016-08-09 오전 9.38.27 스크린샷-4885.png

Python 함수 입문

잘못된 인자 전달

float(2)
2.0
float('2.3')
2.3
float('hello')
<hr />---------------------------------------------------------------
ValueError                       Traceback (most recent call last)
<ipython-input-3-d0ce8bccc8b2> in <module>()
<hr />-> 1 float('hi')
ValueError: could not convert string to float: 'hello'
Python 함수 입문

유효한 인자 전달

def sqrt(x):
    """Returns the square root of a number."""
    return x ** (0.5)
sqrt(4)
2.0
sqrt(10)
3.1622776601683795
Python 함수 입문

무효한 인자 전달

sqrt('hello')
------------------------------------------------------------------
TypeError                        Traceback (most recent call last)
<ipython-input-4-cfb99c64761f> in <module>()
----> 1 sqrt('hello')
<ipython-input-1-939b1a60b413> in sqrt(x)
      1 def sqrt(x):
----> 2     return x**(0.5)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'float'
Python 함수 입문

오류와 예외

  • 예외: 실행 중에 감지됨

  • try-except 절로 예외 처리

    • try 다음 코드 실행

    • 예외가 나면 except 다음 코드 실행

Python 함수 입문

오류와 예외

def sqrt(x):
    """Returns the square root of a number."""
    try:
        return x ** 0.5
    except:
        print('x must be an int or float')

sqrt(4)
2.0
sqrt(10.0)
3.1622776601683795
sqrt('hi')
x must be an int or float
Python 함수 입문

오류와 예외

def sqrt(x):
    """Returns the square root of a number."""
    try:
        return x ** 0.5
    except TypeError:
        print('x must be an int or float')

2016-08-09 오전 10.04.32 스크린샷-4904.png

Python 함수 입문

오류와 예외

sqrt(-9)
(1.8369701987210297e-16+3j)
def sqrt(x):
    """Returns the square root of a number."""
    if x < 0:
        raise ValueError('x must be non-negative')
    try:
        return x ** 0.5
    except TypeError:
        print('x must be an int or float')
Python 함수 입문

오류와 예외

sqrt(-2)
-----------------------------------------------------------------
ValueError                      Traceback (most recent call last)
<ipython-input-2-4cf32322fa95> in <module>()
----> 1 sqrt(-2)
<ipython-input-1-a7b8126942e3> in sqrt(x)
      1 def sqrt(x):
      2     if x < 0:
----> 3         raise ValueError('x must be non-negative')
      4     try:
      5         return x**(0.5)
ValueError: x must be non-negative
Python 함수 입문

Passons à la pratique !

Python 함수 입문

Preparing Video For Download...