'정수인지 확인'에 해당되는 글 1건

  1. 2018.07.14 [Python] 함수 안에 TypeError, ValueError 메시지 지정하기

이번 포스팅에서는 함수 안에 isinstance() 함수를 사용하여 매개변수의 형식(Type)을 확인하고, 함수에서 필요로 하는 데이터 형식이 아니면 에러 메시지를 반환하여 함수 사용자로 하여금 에러를 수정하는데 참고할 수 있는 정보를 제공할 수 있도록 하는 방법에 대해서 소개하겠습니다. 


  • 데이터 형식 확인 함수: isinstance(my_number, int), isinstance(my_string, str)
  • raise TypeError("message")
  • raise ValueError("message")




  (1) 정수형이 아니면 TypeError, 양수가 아니면 ValueError 반환하기


아래의 [1] 번 함수는 숫자를 input으로 넣으면 짝수(even number) 인지 아니면 홀수(odd number) 인지를 판단해주는 예제입니다. 


- if not isinstance(number, int) 조건문 함수를 사용하여 정수인지 여부를 확인하고, 

- if number <= 0 조건문으로 양수가 아닌지를 확인하여 

정수가 아니면 TypeError, 양수가 아니면 ValueError 를 반환하도록 하였습니다. 



In [1]: def even_odd_num_checker(number):

   ...:

   ...:     # TypeError, ValueError handling

   ...:     if not isinstance(number, int):

   ...:         raise TypeError("'number' is not an integer.")

   ...:     if number <= 0:

   ...:         raise ValueError("'number' must be positive.")

   ...:

   ...:     if number % 2 == 0:

   ...:         print("This number is EVEN")

   ...:     else:

   ...:         print("This number is ODD")


In [2]: even_odd_num_checker(10)

This number is EVEN


In [3]: even_odd_num_checker(9)

This number is ODD

 



아래의 [4]번에서는 '10'이라는 문자열을 입력했을 때 TypeError 가 발생한 예이며, [5]번은 매개변수 값으로 5.5 를 입력했을 때 정수(integer)가 아니기 때문에 역시 TypeEror가 발생한 예입니다. 그리고 [6]번 예는 -2 가 양수가 아니기 때문에 ValueError가 발생하였습니다.  위의 [1]번에서 정의한 함수대로 잘 작동하고 있음을 알 수 있습니다. 



In [4]: even_odd_num_checker('10') # TypeError

Traceback (most recent call last):


File "<ipython-input-4-858c9cb910a4>", line 1, in <module>

even_odd_num_checker('10') # TypeError


File "<ipython-input-1-b74b94983114>", line 5, in even_odd_num_checker

raise TypeError("'number' is not an integer.")


TypeError: 'number' is not an integer.



In [5]: even_odd_num_checker(5.5) # TypeError

Traceback (most recent call last):


File "<ipython-input-5-1125bee4ec3f>", line 1, in <module>

even_odd_num_checker(5.5) # ValueError


File "<ipython-input-1-b74b94983114>", line 5, in even_odd_num_checker

raise TypeError("'number' is not an integer.")


TypeError: 'number' is not an integer.

 


In [6]: even_odd_num_checker(-2) # ValueError

Traceback (most recent call last):


File "<ipython-input-6-8bb80e5d6ca4>", line 1, in <module>

even_odd_num_checker(-2) # ValueError


File "<ipython-input-1-b74b94983114>", line 7, in even_odd_num_checker

raise ValueError("'number' must be positive.")


ValueError: 'number' must be positive.





  (2) 문자열이 아니면 TypeError 반환하기


다음으로 [8]번에서 문자열을 매개변수 값으로 입력하면 문자열의 길이를 반환해주는 함수를 정의해보겠습니다. 이때 매개변수 값이 문자열(string)이 아니면 TypeError 를 반환하도록 하였습니다. 


[9]번에서 string_length() 함수에 "hello world" 값을 넣으니 길이가 11이라고 정상적으로 작동함을 알 수 있습니다. 



In [7]: import sys


In [8]: def string_length(string_input):

   ...:

   ...: # Python version check

   ...:     if sys.version_info[0] == 3:

   ...:         string_arg = str # Python 3x version

   ...:     else:

   ...:         string_arg = basestring # Python 2x version

   ...:

   ...: # TypeError handling

   ...:     if not isinstance(string_input, string_arg):

   ...:         raise TypeError("'string' is not a string")

   ...:

   ...:     string_length = len(string_input)

   ...:     print("The length of the string is {0}".format(string_length))


In [9]: string_length("hello world")

The length of the string is 11

 



[10]번에서 string_length() 함수에 숫자 10을 넣으면 문자열이 아닌 정수형이므로 TypeError 메시지를 반환합니다. 



In [10]: string_length(10) # TypeError

Traceback (most recent call last):


File "<ipython-input-10-997e19d6acd3>", line 1, in <module>

string_length(10) # TypeError


File "<ipython-input-8-8363558b8e40>", line 11, in string_length

raise TypeError("'string' is not a string")


TypeError: 'string' is not a string

 


많은 도움이 되었기를 바랍니다. 

728x90
반응형
Posted by Rfriend
,