Python 에서 변수가 부동 소수점인지 확인하는 방법

PythonBeginner
지금 연습하기

소개

이 랩에서는 Python 에서 변수가 float 인지 확인하는 방법을 배우게 됩니다. 랩은 부동 소수점 숫자와 소수점을 가진 실수를 표현하는 데 있어 그 중요성을 소개하는 것으로 시작합니다.

먼저 floats.py 파일을 생성하고 pi, gravity, temperature와 같은 변수에 부동 소수점 값을 할당하는 것으로 시작합니다. 그런 다음 이러한 변수를 사용하여 덧셈, 뺄셈, 곱셈 및 나눗셈과 같은 기본적인 산술 연산을 수행하고 결과를 관찰합니다. 마지막으로, 랩에서는 type()isinstance()를 사용하여 변수가 실제로 float 인지 확인하는 방법을 안내합니다.

부동 소수점 숫자 (Floating-Point Numbers) 에 대해 알아보기

이 단계에서는 Python 에서 부동 소수점 숫자 (floating-point numbers) 에 대해 배우게 됩니다. 부동 소수점 숫자는 소수점이 있는 숫자를 포함하는 실수를 나타내는 데 사용됩니다. 부동 소수점 숫자를 사용하는 방법을 이해하는 것은 많은 유형의 계산에 매우 중요합니다.

부동 소수점 숫자를 실험하기 위해 Python 파일을 만들어 보겠습니다.

  1. LabEx 환경에서 VS Code 편집기를 엽니다.
  2. ~/project 디렉토리에 floats.py라는 새 파일을 만듭니다.

이제 floats.py에 코드를 추가해 보겠습니다.

## Assigning floating-point numbers to variables
pi = 3.14159
gravity = 9.8
temperature = 25.5

## Printing the values
print("Pi:", pi)
print("Gravity:", gravity)
print("Temperature:", temperature)

이 코드에서는 부동 소수점 값을 pi, gravity, temperature의 세 변수에 할당했습니다. 그런 다음 print() 함수를 사용하여 이러한 값을 표시합니다.

스크립트를 실행하려면 VS Code 에서 터미널을 열고 (일반적으로 "View" -> "Terminal" 메뉴에서 찾을 수 있습니다) 다음 명령을 실행합니다.

python floats.py

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

Pi: 3.14159
Gravity: 9.8
Temperature: 25.5

이제 부동 소수점 숫자를 사용하여 몇 가지 기본적인 산술 연산을 수행해 보겠습니다.

## Addition
result_addition = pi + gravity
print("Addition:", result_addition)

## Subtraction
result_subtraction = gravity - temperature
print("Subtraction:", result_subtraction)

## Multiplication
result_multiplication = pi * temperature
print("Multiplication:", result_multiplication)

## Division
result_division = gravity / 2
print("Division:", result_division)

이 줄을 floats.py 파일에 추가하고 다시 실행합니다.

python floats.py

다음과 유사한 출력을 볼 수 있습니다.

Pi: 3.14159
Gravity: 9.8
Temperature: 25.5
Addition: 12.94159
Subtraction: -15.7
Multiplication: 80.110545
Division: 4.9

부동 소수점 숫자는 과학적 표기법 (scientific notation) 을 사용하여 표현할 수도 있습니다.

## Scientific notation
avogadro = 6.022e23
print("Avogadro's number:", avogadro)

이것을 floats.py 파일에 추가하고 실행합니다.

python floats.py

출력은 다음과 같습니다.

Pi: 3.14159
Gravity: 9.8
Temperature: 25.5
Addition: 12.94159
Subtraction: -15.7
Multiplication: 80.110545
Division: 4.9
Avogadro's number: 6.022e+23

이것은 기본적인 산술 연산과 과학적 표기법을 포함하여 Python 에서 부동 소수점 숫자를 정의하고 사용하는 방법을 보여줍니다.

type() 함수로 확인하기

이 단계에서는 Python 에서 type() 함수를 사용하여 변수의 데이터 유형을 결정하는 방법을 배우게 됩니다. 이는 다양한 유형의 숫자로 작업하고 있으며 올바른 연산을 수행하고 있는지 확인하려는 경우 특히 유용합니다.

이전 단계에서 생성한 floats.py 파일을 계속 사용해 보겠습니다. 부동 소수점 변수의 유형을 확인하는 코드를 추가할 것입니다.

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

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

## Checking the type of variables
print("Type of pi:", type(pi))
print("Type of gravity:", type(gravity))
print("Type of temperature:", type(temperature))

## Checking the type of the result of addition
print("Type of result_addition:", type(result_addition))

이 코드에서는 type() 함수를 사용하여 변수 pi, gravity, temperature, result_addition의 데이터 유형을 결정합니다. 그런 다음 print() 함수가 데이터 유형을 표시합니다.

이제 스크립트를 실행합니다.

python floats.py

다음과 유사한 출력을 볼 수 있습니다.

Pi: 3.14159
Gravity: 9.8
Temperature: 25.5
Addition: 12.94159
Subtraction: -15.7
Multiplication: 80.110545
Division: 4.9
Avogadro's number: 6.022e+23
Type of pi: <class 'float'>
Type of gravity: <class 'float'>
Type of temperature: <class 'float'>
Type of result_addition: <class 'float'>

보시다시피 type() 함수는 이러한 모든 변수가 float 유형임을 확인합니다.

이제 정수가 있는 경우 어떻게 되는지 살펴보겠습니다.

## Integer variable
integer_number = 10
print("Type of integer_number:", type(integer_number))

이것을 floats.py 파일에 추가하고 실행합니다.

python floats.py

이제 출력에 다음이 포함됩니다.

Pi: 3.14159
Gravity: 9.8
Temperature: 25.5
Addition: 12.94159
Subtraction: -15.7
Multiplication: 80.110545
Division: 4.9
Avogadro's number: 6.022e+23
Type of pi: <class 'float'>
Type of gravity: <class 'float'>
Type of temperature: <class 'float'>
Type of result_addition: <class 'float'>
Type of integer_number: <class 'int'>

이것은 integer_numberint 유형임을 보여줍니다. type() 함수는 Python 에서 작업하는 데이터 유형을 이해하는 데 유용한 도구입니다.

isinstance() 함수를 사용하여 부동 소수점 확인하기

이 단계에서는 Python 에서 isinstance() 함수를 사용하여 변수가 특정 유형인지 확인하는 방법을 배우게 됩니다. 이는 type()을 직접 사용하는 것보다 데이터 유형을 확인하는 더 강력한 방법이며, 특히 상속 및 복잡한 유형 계층 구조를 다룰 때 유용합니다.

이전 단계에서 사용해 온 floats.py 파일을 계속 사용해 보겠습니다.

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

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

## Checking if a variable is a float using isinstance()
print("Is pi a float?", isinstance(pi, float))
print("Is gravity a float?", isinstance(gravity, float))
print("Is temperature a float?", isinstance(temperature, float))

## Checking if a variable is an integer using isinstance()
print("Is integer_number an integer?", isinstance(integer_number, int))

## Checking if a variable is a number (int or float)
print("Is pi a number?", isinstance(pi, (int, float)))
print("Is integer_number a number?", isinstance(integer_number, (int, float)))

이 코드에서는 isinstance() 함수를 사용하여 변수 pi, gravity, temperature, integer_numberfloat 또는 int 유형인지 확인합니다. isinstance() 함수는 두 개의 인수를 받습니다. 확인할 변수와 확인할 유형 (또는 유형의 튜플) 입니다. 변수가 지정된 유형인 경우 True를 반환하고, 그렇지 않으면 False를 반환합니다.

이제 스크립트를 실행합니다.

python floats.py

다음과 유사한 출력을 볼 수 있습니다.

Pi: 3.14159
Gravity: 9.8
Temperature: 25.5
Addition: 12.94159
Subtraction: -15.7
Multiplication: 80.110545
Division: 4.9
Avogadro's number: 6.022e+23
Type of pi: <class 'float'>
Type of gravity: <class 'float'>
Type of temperature: <class 'float'>
Type of result_addition: <class 'float'>
Type of integer_number: <class 'int'>
Is pi a float? True
Is gravity a float? True
Is temperature a float? True
Is integer_number an integer? True
Is pi a number? True
Is integer_number a number? True

보시다시피 isinstance()는 변수의 데이터 유형을 올바르게 식별합니다. 또한 두 번째 인수로 유형의 튜플을 전달하여 변수가 여러 유형 중 하나인지 확인하는 방법도 보여줍니다. 이는 다양한 유형의 입력을 처리할 수 있는 유연하고 강력한 코드를 작성하기 위한 강력한 도구입니다.

요약

이 랩에서는 소수점을 사용하여 실수 (real number) 를 나타내는 Python 의 부동 소수점 숫자 (floating-point numbers) 에 대해 배웠습니다. pi, gravity, temperature와 같은 변수에 부동 소수점 값을 할당하고 이러한 값을 출력하기 위해 floats.py 파일을 만들었습니다.

또한 이 랩에서는 덧셈, 뺄셈, 곱셈 및 나눗셈을 포함하여 부동 소수점 숫자를 사용한 기본적인 산술 연산에 대해서도 다루었습니다. floats.py 스크립트를 실행하여 이러한 연산의 결과를 관찰했습니다.