-
데이터 타입(자료형 검사)Python 2023. 3. 18. 23:56
int와 string이 뒤석여있는 배열을 for 문을 활용해서 int 값들만 합을 구하는 문제가 있었다.
numbers = [ int와 string이 뒤 섞인 값들 ] sum_result = 0 for num in numbers: if isinstance(num,int): sum_result = sum_result + num print(sum_result)
- 다음과 같이 for 문 내부에 if문으로 배열의 값이 int인지 아닌지 검사하는 명령어를 넣어서 해결했다.
python에서 타입을 확인하는 방법 두가지가 있다
type 과 isinstance 이다. 둘의 차이점으로 type은 해당 데이터의 type을 반환하고 isinstance는 true/false로 반환한다
type(데이터) -> 데이터의 타입을 반환해준다 ( int , string , float , list 등 ) 만약 두개의 데이터 타입을 비교하고 싶다면, type(A) == type(B) 의 형식을 이용해야한다. - isinstance( 데이터 , 타입명 ) -> 함수에 넣은 데이터와 타입이 일치하면 True, 일치하지 않으면 Flase를 리턴한다. isinstance( 데이터 , (타입명 , 타입명, 타입명) ) -> 만일 튜플 형식으로 타입명을 여러개 넣는 경우 타입들 중 한 가지만 데이터와 일치해도 True를 반환한다. ( or 과 비슷한 역할 )
'Python' 카테고리의 다른 글
User-Agent 지정 ( header ) (0) 2023.03.20 input 자료형 검증 ( try - excpt ) (0) 2023.03.16 nomard) python기초 ( ERROR 모음 ) (0) 2023.03.10 nomard) python기초 (Flask로 웹페이지 만들기) (0) 2023.03.10 nomad) python 기초 (2) (0) 2023.03.06