HOWTO · Python

Python ValueError:Float()에 대한 유효하지 않은 리터럴

이 기사에서는 float()에 대한 ValueError 유효하지 않은 리터럴이 무엇이며 이를 해결하는 방법에 대해 알아봅니다. 이 오류는 float() 함수에서 인식하지 못하는 잘못된 리터럴을 float() 함수에 전달할 때 발생합니다.

이 페이지의 내용

float() 함수에서 지원하지 않는 인식할 수 없는 인수를 전달하면 Python 컴파일러에서 ValueError: invalid literal for float()과 같은 오류가 발생합니다. Python 컴파일러는 문자열 값을 float()에 인수로 전달할 때 Python 2x 버전에서 ValueError: invalid literal for float() 및 Python 3x 버전에서 ValueError: could not convert string to float를 발생시킵니다. 기능.

Python의 ValueError: invalid literal for float()

float() 함수는 문자열을 부동 소수점 숫자로 형 변환할 수 없습니다. 오히려 Python 버전에 따라 다를 수 있는 ValueError를 발생시킵니다.

Python 2Python 3에 대한 예를 살펴보겠습니다.

코드 - Python 2:

# python 2.7
import sys

print("The Current version of Python:", sys.version)

x = "123xyx"
y = float(x)
print(y)

출력:

The current version of Python: 2.7.18
ValueError: invalid literal for float(): 123xyx

코드 - Python 3:

# >= Python 3.7
import sys

print("The Current version of Python:", sys.version)

x = "123xyx"
y = float(x)
print(y)

출력:

The current version of Python: 3.7.4
ValueError: could not convert string to float: '123xyx'

Python 2.7Python 3.7에서 동일한 코드를 실행했지만 Python 컴파일러의 개선 및 지속적인 개발로 인해 오류가 동일하지 않습니다.

Python에서 ValueError: invalid literal for float() 수정

invalid literal for float() 또는 could not convert string to float 값 오류를 수정하려면 float() 함수에 대한 인수로 유효한 리터럴을 제공해야 올바르게 구문 분석할 수 있습니다.

완벽하게 작동하도록 float 함수에 유효한 숫자 문자열(숫자만) 또는 정수 값을 제공할 수 있습니다.

암호:

h = input("Enter you height:")
print(type(h))

height = float(h)
print("\nYour height is:", height)
print(type(height))

출력:

Enter you height:5.4
<class 'str'>

Your height is: 5.4
<class 'float'>

높이의 값은 항상 부동 소수점이지만 입력 문은 모든 입력을 문자열로 받아들입니다. 따라서 위의 경우 사용자는 클래스가 str인 높이 "5.4"를 입력했지만 나중에 'float'로 유형 변환했습니다.