Getting a TypeError: '<=' not supported between instances of 'NoneType' and 'int'

Getting a TypeError: '<=' not supported between instances of 'NoneType' and 'int'

我是 python 初学者,我不明白这段代码的错误。

我正在尝试使用平分线法找到等于或尽可能接近 100mm/0.1m 的 x 值。

这是我的错误:

如果 z <= 100:

TypeError:'NoneType' 和 'int'

实例之间不支持“<=”

代码:

xL, xR = 0, 10
m= 800
k=5E6
xM = (xL + xR)/2

def dispcalc(m,k,xM):    #Dispalcement Function
    xL, xR = 0, 10       # Initial x Left and x Right

    xM = (xL + xR) / 2     #Midpoint of xL and xR
    print(xM)

z = (dispcalc(m,k,xM))
while z != 100:
    xM = (xL + xR) /2
    if z <= 100:
        xR=xM
        xM = (xL + xR) / 2
        z = dispcalc(800, 5E6, xM)
       
    else:
        xL = xM
        xM = (xL + xR) / 2
        z = dispcalc(800, 5E6, xM)
       
    dispcalc(800, 5E6, xM)
    print(xM, z)

或者如果我在 def dispcalc 函数中使用 while 循环,另一个错误是代码不打印任何内容。

xL, xR = 0, 10
m= 800
k=5E6
xM = (xL + xR)/2

def dispcalc(m,k,xM):    #Dispalcement Function
    xL, xR = 0, 10       # Initial x Left and x Right

    xM = (xL + xR) / 2     #Midpoint of xL and xR
    print(xM)
    z = (dispcalc(m,k,xM))
    while z != 100:
        xM = (xL + xR) /2
        if z <= 100:
            xR=xM
            xM = (xL + xR) / 2
            z = dispcalc(800, 5E6, xM)
        
        else:
            xL = xM
            xM = (xL + xR) / 2
            z = dispcalc(800, 5E6, xM)
        
        dispcalc(800, 5E6, xM)
        print(xM, z)
        

您的函数 dispcalc 缺少 return 语句。当前,您执行一些计算并打印结果,但不在内存中保留对此类结果的任何引用,这正是 return 所做的。因此,dispcalc returns None。然后将该值 ( None) 分配给变量 z,这就是您收到该错误的原因。

正确的代码(在您的第一个片段中):


def dispcalc(m,k,xM):    #Dispalcement Function
    xL, xR = 0, 10       # Initial x Left and x Right

    xM = (xL + xR) / 2     #Midpoint of xL and xR
    print(xM)  #this is in fact not needed
    return(xM)