Python 3用type()识别float

0 python types python-3.x

这是我在麻省理工学院开放式课程计算机科学第7讲中遇到的一段代码.这个小程序得到基数和高度的输入然后用毕达哥拉斯定理计算斜边.

由于某种原因,它无法识别浮动的进入.

代码如下:

#! /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5
import math

#Get base
inputOK = False
while not inputOK:
    base = input("Enter base: ")
    if type(base) == type(1.0):
        inputOK = True
    else:
        print("Error. Base must be a floating point number.")

#Get Height
inputOK = False
while not inputOK:
    height = input("Enter height: ")
    if type(height) == type(1.0):
        inputOK = True
    else:
        print("Error. height must be a floating point number.")

hyp = math.sqrt(base*base + height*height)

print("Base: " + str(base) + ", height: " + str(height) + ", hypotenuse:" + str(hyp))
Run Code Online (Sandbox Code Playgroud)

Jim*_*ard 6

在这种情况下,请求宽恕比获得更容易.在你行动之前,不要试图查看对象并断言它是一个浮点数,尝试将它用作浮点数并捕获任何异常.

也就是说,而不是使用ifs:

try:
    base = float(base)
    inputOK = True
except ValueError as e:
    print("Error. Base must be a floating point number.")
Run Code Online (Sandbox Code Playgroud)

这同样适用于height您之后尝试获得的值.

无论如何,input()返回一个字符串,所以type(input())将始终返回str.最好将它转换为浮点数(注意:ints也适用于浮点数)并查看是否可以接受,而不是尝试通过if检查识别其类型.

强制性的,如果你甚至需要检查类型,不要使用type(obj_a) == type(obj_b),它可以说总是更好用isinstance(obj_a, type(obj_b)).