TypeError:python 3中需要一个float

时间:2017-11-22 22:40:46

标签: python-3.x math typeerror

我有一个Python3脚本如下:

import math

Value_1 = float(input("what's the X1 value?")), float(input("what's the X2 value?"))

Value_2 = float(input("what's the Y1 value?")), float(input("what's the Y2 value?"))

equation =(math.sqrt(math.sqrt(Value_1)+ math.sqrt(Value_2)))

print (equation)

使用此输出

  

什么是X1值?3.0

     

什么是X2值?12.0

     

什么是Y1值?10.0

     

什么是Y2值?110.0

然后程序返回此错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-15-cc8d8b28ff67> in <module>()
      5 
      6 
----> 7 equation = float(math.sqrt(math.sqrt(Value_1)+ math.sqrt(Value_2)))
      8 
      9 print (equation)

TypeError: a float is required

我已尝试将所有提示用于其他问题,但错误仍然存​​在。有什么提示吗?

2 个答案:

答案 0 :(得分:1)

没有人关心我的问题,但我自己弄清楚了。我们走了:

import math

x1 = float(input("what's the X1 value?"))

x2 = float (input("what's the X2 value?"))

print (x2 - x1)

xdiff = abs (x2 - x1)

print (xdiff)

y1 = float(input("what's the y1 value?"))

y2 = float (input("what's the y2 value?"))

ydiff = abs(y2 - y1)
print (ydiff)


math.sqrt(math.pow(xdiff,2) + math.pow(ydiff,2))

答案 1 :(得分:0)

有什么问题?

通过分配给逗号分隔的Value_1输入,您将定义一个元组。作为一个简短的例子:

In [1]: tup = 42, 23

In [2]: type(tup)
Out[2]: tuple

但是,math.sqrt函数需要浮点值作为输入,而不是元组。

如何解决此问题

您可以使用元组解压缩来保持原始帖子的结构不变:

import math

# read in x and y value of the first point and store them in a tuple
point_1 = float(input("What is the x value of point 1? ")), float(input("What is the y value of point 1? "))
# read in x and y value of the second point and store them in a tuple
point_2 = float(input("What is the x value of point 2? ")), float(input("What is the y value of point 2? "))

# This is where the tuple unpacking happens.
# After this you have the x and y values
# of the points in their respective variables.
p1_x, p1_y = point_1
p2_x, p2_y = point_2

# At this point you can use point_1 when you need both x and y value of
# of the first point. If you need only the x or y value you can use the
# unpacked coordinates saved in p1_x and p1_y respectively.

x_diff = abs(p1_x - p2_x)
y_diff = abs(p1_y - p2_y)

distance = math.sqrt(math.pow(x_diff, 2) + math.pow(y_diff, 2))
print("Distance of {} and {} is {}".format(point_1, point_2, distance))

正如您在上面所看到的那样,将点的信息首先保存为元组然后在不同的点使用解压缩的坐标会很有帮助。

我希望这能说明发生的事情。