为什么会出现不支持的操作数类型错误?
好的,我有一个关于Python的小练习,我想要在一个列表中找到从0秒到30秒之间每一秒的速度和位置的值。同时,当它们相交时,也要提醒我。在计算第一辆车的位置时,我只能使用梯形法的代码。
第一辆车的速度公式是 V1=t^3-3*t^2+2*t,第二辆车的速度公式是 V2=10*t。
我的代码:
def cars():
def LocationV1(x):
x=x*1.0
h=x/1000.0
m=0
n=m+h
L=0.0
for i in range (0,1000):
def f(u):
return u**3+3*u**2+2*u
L=L+(f(m)+f(n))*h/2
m=m+h
n=n+h
return L
def LocationV2(x):
x=x*1.0
def g(x):
return 5*x**2/2
def SpeedV1 (x):
x=x*1.0
return x**3-3*x**2+2*x
def SpeedV2 (x):
x=x*1.0
return 10*x
V1=[]
V2=[]
t=0
a=LocationV1(t)
b=LocationV2(t)
while t<=30:
t=t+1
V1=V1+[[LocationV1(t), SpeedV1(t), t]]
V2=V2+[[LocationV2(t), SpeedV2(t), t]]
print V1
print V2
if (a-b)<=0.1:
print "cars meet"
当我使用这段代码时,它给了我这样的错误:
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
cars()
File "C:/Users/ÖZGÜR/Desktop/ödev", line 35, in cars
if (a-b)<=1:
TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'
那我现在该怎么办?
6 个回答
0
LocationV2
这个东西没有返回任何值,所以 b
的值就是 None
。
2
b=LocationV2(t)
问题是,这个返回的是 None
,所以 a-b
就会出现你遇到的错误。
def LocationV2(x):
x=x*1.0
def g(x):
return 5*x**2/2
应该改成:
def LocationV2(x):
x=x*1.0
return 5*x**2/2
这样就能解决你的问题了。
2
我不太懂Python,但你的函数 LocationV2()
看起来没有返回任何东西。