본문 바로가기
카테고리 없음

python float() 함수소개

by python pro 2023. 2. 5.
반응형

Python의 float() 함수는 주어진 값을 부동 소수점 숫자로 변환해주는 함수입니다.

올바른 코드 예시로는, 숫자형(int, long) 또는 문자열 형태의 숫자를 float로 변환할 수 있습니다.

x = float(5)
print(x) # 5.0

y = float('3.14')
print(y) # 3.14

z = float(4+5j)
print(z) # TypeError: can't convert complex to float

 

잘못된 코드 예시로는, 변환 할 수 없는 타입의 값을 float() 함수에 전달하면 TypeError가 발생합니다.

a = float('hello')
print(a) # ValueError: could not convert string to float: 'hello'

b = float(['1', '2', '3'])
print(b) # TypeError: float() argument must be a string or a number, not 'list'

 

float() 함수는 숫자 변환을 위해서만 사용되는 것이 아니라, 서로 다른 타입의 데이터를 통일된 타입으로 변환하는 경우에도 사용됩니다.

예를 들어, 사용자로부터 입력받은 문자열 형태의 숫자를 실수로 사용하기 위해서는 float() 함수를 사용하면 됩니다.

weight = input("Your weight: ")
weight = float(weight)
print(weight) # Your weight: 75

 

데이터를 읽어올 때 정수나 문자열로 저장되어 있는 값을 실수로 변환해서 사용할 수 있습니다. 아래는 CSV 파일에서 읽어들인 데이터를 실수로 변환해서 사용하는 예제입니다.

import csv

# CSV 파일 읽어들이기
with open("data.csv") as f:
    reader = csv.reader(f)
    for row in reader:
        # 첫번째 열을 실수로 변환
        value = float(row[0])
        print(value)
반응형

댓글