파이썬에서 숫자가 정수인지 (부동 소수점이 아닌지) 확인하는 방법

PythonBeginner
지금 연습하기

소개

이 랩에서는 Python 에서 숫자가 정수 (integer) 인지 부동 소수점 (float) 인지 확인하는 방법을 배우게 됩니다. 랩은 정수와 부동 소수점의 주요 특징을 강조하고 예시를 제공하면서 두 유형을 구별하는 것으로 시작합니다.

그런 다음 숫자의 데이터 유형을 확인하는 두 가지 방법, 즉 int와 함께 isinstance() 함수를 사용하고 정밀도를 위해 type() 함수를 사용하는 방법을 살펴보겠습니다. 실습을 통해 정수 및 부동 소수점 데이터 유형을 식별하고 구별하는 Python 스크립트를 생성하여 Python 에서 데이터 유형 검증에 대한 이해를 굳힐 것입니다.

정수와 부동 소수점 구분

이 단계에서는 Python 의 두 가지 기본 데이터 유형인 정수 (integer) 와 부동 소수점 (float) 을 구별하는 방법을 배우게 됩니다. 정확한 계산과 데이터 조작을 수행하려면 이러한 차이점을 이해하는 것이 중요합니다.

정수 (int)

정수는 소수점이 없는 양수 또는 음수의 전체 숫자입니다. 예시로는 -3, 0, 5, 100 등이 있습니다.

부동 소수점 (float)

부동 소수점 또는 부동 소수점 숫자는 소수점을 포함하는 숫자입니다. 과학적 표기법으로 숫자를 나타낼 수도 있습니다. 예시로는 -2.5, 0.0, 3.14, 1.0e5 (100000.0) 등이 있습니다.

이러한 데이터 유형을 탐구하기 위해 Python 스크립트를 만들어 보겠습니다.

  1. LabEx 환경에서 VS Code 편집기를 엽니다.

  2. ~/project 디렉토리에 datatypes.py라는 새 파일을 만듭니다.

    touch ~/project/datatypes.py
    
  3. 편집기에서 datatypes.py 파일을 열고 다음 Python 코드를 추가합니다.

    ## Assign an integer to the variable 'integer_number'
    integer_number = 10
    
    ## Assign a float to the variable 'float_number'
    float_number = 10.0
    
    ## Print the values and their types
    print("Integer:", integer_number, "Type:", type(integer_number))
    print("Float:", float_number, "Type:", type(float_number))
    
  4. datatypes.py 파일을 저장합니다.

  5. 터미널에서 python 명령을 사용하여 스크립트를 실행합니다.

    python ~/project/datatypes.py
    

    다음과 같은 출력을 볼 수 있습니다.

    Integer: 10 Type: <class 'int'>
    Float: 10.0 Type: <class 'float'>
    

    이 출력은 integer_numberint 유형이고 float_numberfloat 유형임을 명확하게 보여줍니다.

  6. 이제 Python 이 이러한 유형을 어떻게 처리하는지 확인하기 위해 간단한 산술 연산을 수행해 보겠습니다.

    datatypes.py 파일을 수정하여 다음을 포함합니다.

    ## Assign an integer to the variable 'integer_number'
    integer_number = 10
    
    ## Assign a float to the variable 'float_number'
    float_number = 10.0
    
    ## Print the values and their types
    print("Integer:", integer_number, "Type:", type(integer_number))
    print("Float:", float_number, "Type:", type(float_number))
    
    ## Add an integer and a float
    sum_result = integer_number + float_number
    
    ## Print the result and its type
    print("Sum:", sum_result, "Type:", type(sum_result))
    
  7. datatypes.py 파일을 저장합니다.

  8. 스크립트를 다시 실행합니다.

    python ~/project/datatypes.py
    

    다음과 같은 출력을 볼 수 있습니다.

    Integer: 10 Type: <class 'int'>
    Float: 10.0 Type: <class 'float'>
    Sum: 20.0 Type: <class 'float'>
    

    정수와 부동 소수점을 더하면 결과가 부동 소수점이 됩니다. 이는 Python 이 정밀도를 유지하기 위해 자동으로 정수를 부동 소수점으로 변환하기 때문입니다.

isinstance() 함수와 int 사용

이 단계에서는 isinstance() 함수를 사용하여 변수가 정수인지 확인하는 방법을 배우게 됩니다. 이 함수는 Python 에서 데이터 유형을 확인하는 강력한 도구입니다.

isinstance() 함수는 두 개의 인수를 사용합니다.

  • 확인하려는 변수.
  • 확인하려는 데이터 유형 (예: int, float, str).

변수가 지정된 유형인 경우 True를 반환하고, 그렇지 않으면 False를 반환합니다.

이전 단계에서 datatypes.py 파일을 수정하여 isinstance() 함수를 포함해 보겠습니다.

  1. VS Code 편집기에서 datatypes.py 파일을 엽니다.

  2. 다음 코드를 파일에 추가합니다.

    ## Assign an integer to the variable 'integer_number'
    integer_number = 10
    
    ## Assign a float to the variable 'float_number'
    float_number = 10.0
    
    ## Print the values and their types
    print("Integer:", integer_number, "Type:", type(integer_number))
    print("Float:", float_number, "Type:", type(float_number))
    
    ## Add an integer and a float
    sum_result = integer_number + float_number
    
    ## Print the result and its type
    print("Sum:", sum_result, "Type:", type(sum_result))
    
    ## Check if integer_number is an integer
    is_integer = isinstance(integer_number, int)
    print("Is integer_number an integer?", is_integer)
    
    ## Check if float_number is an integer
    is_integer = isinstance(float_number, int)
    print("Is float_number an integer?", is_integer)
    
  3. datatypes.py 파일을 저장합니다.

  4. 터미널에서 python 명령을 사용하여 스크립트를 실행합니다.

    python ~/project/datatypes.py
    

    다음과 같은 출력을 볼 수 있습니다.

    Integer: 10 Type: <class 'int'>
    Float: 10.0 Type: <class 'float'>
    Sum: 20.0 Type: <class 'float'>
    Is integer_number an integer? True
    Is float_number an integer? False
    

    보시다시피, isinstance(integer_number, int)integer_number가 실제로 정수이므로 True를 반환합니다. isinstance(float_number, int)float_number가 정수가 아닌 부동 소수점이므로 False를 반환합니다.

이 함수는 변수의 데이터 유형에 따라 다른 작업을 수행해야 할 때 특히 유용합니다. 예를 들어, 변수가 정수이면 정수 나눗셈을 수행하고, 부동 소수점이면 부동 소수점 나눗셈을 수행할 수 있습니다.

정확성을 위해 type() 으로 확인

이 단계에서는 type() 함수를 사용하여 Python 에서 숫자의 정밀도를 이해하는 방법을 살펴봅니다. isinstance()가 변수가 특정 유형에 속하는지 확인하는 반면, type()은 변수의 실제 유형을 반환합니다. 이는 Python 이 다양한 숫자 연산과 그 결과로 나타나는 정밀도를 처리하는 방식을 이해하는 데 유용합니다.

이를 보여주기 위해 datatypes.py 파일을 계속 수정해 보겠습니다.

  1. VS Code 편집기에서 datatypes.py 파일을 엽니다.

  2. 다음 코드를 파일에 추가합니다.

    ## Assign an integer to the variable 'integer_number'
    integer_number = 10
    
    ## Assign a float to the variable 'float_number'
    float_number = 10.0
    
    ## Print the values and their types
    print("Integer:", integer_number, "Type:", type(integer_number))
    print("Float:", float_number, "Type:", type(float_number))
    
    ## Add an integer and a float
    sum_result = integer_number + float_number
    
    ## Print the result and its type
    print("Sum:", sum_result, "Type:", type(sum_result))
    
    ## Check if integer_number is an integer
    is_integer = isinstance(integer_number, int)
    print("Is integer_number an integer?", is_integer)
    
    ## Check if float_number is an integer
    is_integer = isinstance(float_number, int)
    print("Is float_number an integer?", is_integer)
    
    ## Perform division with integers
    division_result = integer_number / 3
    print("Division result:", division_result, "Type:", type(division_result))
    
    ## Perform integer division with integers
    integer_division_result = integer_number // 3
    print("Integer division result:", integer_division_result, "Type:", type(integer_division_result))
    
  3. datatypes.py 파일을 저장합니다.

  4. 터미널에서 python 명령을 사용하여 스크립트를 실행합니다.

    python ~/project/datatypes.py
    

    다음과 같은 출력을 볼 수 있습니다.

    Integer: 10 Type: <class 'int'>
    Float: 10.0 Type: <class 'float'>
    Sum: 20.0 Type: <class 'float'>
    Is integer_number an integer? True
    Is float_number an integer? False
    Division result: 3.3333333333333335 Type: <class 'float'>
    Integer division result: 3 Type: <class 'int'>
    

    다음 사항에 유의하십시오.

    • / 연산자를 사용하여 두 개의 정수를 나누면 결과가 정수이더라도 결과는 부동 소수점이 됩니다. 이는 Python 이 가능한 가장 정확한 결과를 제공하려고 하기 때문입니다.
    • // 연산자 (정수 나눗셈) 를 사용하면 결과는 정수가 되며, 소수 부분은 버려집니다.

이러한 미묘한 차이를 이해하는 것은 특히 숫자 계산을 처리할 때 정확하고 효율적인 Python 코드를 작성하는 데 중요합니다.

요약

이 랩에서는 Python 에서 정수와 부동 소수점을 구별하는 방법을 배웠습니다. 정수는 소수점이 없는 정수이고, 부동 소수점은 소수점을 포함하는 숫자입니다. Python 스크립트를 생성하여 정수 및 부동 소수점 값을 변수에 할당한 다음, type() 함수를 사용하여 해당 값과 해당 유형을 출력했습니다. 출력 결과는 정수를 할당한 변수는 int 유형이고, 소수점이 있는 변수는 float 유형임을 보여주었습니다.