python:无法将字符串转换为float

时间:2016-10-18 19:07:28

标签: python string input floating-point

我提交此代码..

a = float(input())
b = float(input())
c = float(input())

if abs(b - c) < a < (b + c) and abs(a - c) < b < (a + c) and abs(a - b) < c < (a + b):
    print("Perimetro = " + str(a + b + c))
else:
    print("Area = " + str(((a + b) * c) / 2))

对我来说这是正确的,但作为回应,我得到了:

Traceback (most recent call last):
  File "Main.py", line 1, in <module>
    a = float(input())
ValueError: could not convert string to float: '6.0 4.0 2.0'
Command exited with non-zero status (1)

我得不到它,因为我在开始时转换了字符串。

我在这里做错了什么?

谢谢x

1 个答案:

答案 0 :(得分:0)

问题是您一次输入所有三个值。添加一个值,然后按Enter键。例如:

>>> a = float(input())
6.0
>>> b = float(input())
4.0
>>> c = float(input())
2.0
>>> a, b, c
(6.0, 4.0, 2.0)

或者,获取单个字符串并使用split字符串将值分配给abc。例如:

>>> a, b, c = [float(item) for item in input().split()]
6.0 4.0 2.0
>>> a, b, c
(6.0, 4.0, 2.0)