I am a python beginner and I do not understand the error I am getting for this code.
I am trying to find an x value equal to or as close to 100mm/0.1m as possible using the bisector method.
This is my error:
if z <= 100:
TypeError: '<=' not supported between instances of 'NoneType' and 'int'
Code:
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)
Or the other error is the code prints nothing, if i use the while loop within the def dispcalc function.
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)
CodePudding user response:
Your function dispcalc
is lacking a return
statement. Currently, you perform some calculations and print the result, but do not keep any reference to such result in memory, which is what return
does. Thus, dispcalc
returns None
. Then you assign that value ( None
) to the variable z
and that's why you get that error.
Correct code (in your first snippet):
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)