[英]Using elif statement "print function" not working correctly instead printing if statement's "print function" instead
[英]Print statement in function not working
我试图定义一个函数,该函数计算两个粒子之间的距离并打印出包含距离的表格。 但是,当我使用该功能时,没有打印任何内容。 我究竟做错了什么?
au = 1.49598e11 #astronomical unit in meters
rx = au * np.asarray([.5,.8,.2]) #x-comp separation vector
ry = au * np.asarray([2.6,9.1,3.7]) #y-comp separation vector
rz = au * np.asarray([.05,.1,.25]) #z-comp separation vector
def svec(x,y,z):
'''computes the magnitude and vector components of the distance between two particles.'''
#for loop to compute vector components of separation between two particles
rvec = []
for i in range(3):
if i < 2:
vx = x[i]-x[i+1]
vy = y[i]-y[i+1]
vz = z[i]-z[i+1]
rvec.append([vx,vy,vz])
if i == 2:
vx = x[0]-x[-1]
vy = y[0]-y[-1]
vz = z[0]-z[-1]
rvec.append([vx,vy,vz])
return rvec
comp1 = ['x-comp[m]','y-comp[m]','z-comp[m]']
r0 = rvec[0].insert(0,'particle 0->1')
r1 = rvec[1].insert(0,'particle 1->2')
r2 = rvec[2].insert(0,'particle 0->2')
print(tabulate(rvec,headers=comp1))
Python对空格敏感,但是文档字符串可能会由于缩进而导致您无法获得适当的错误。
看起来您的代码应该像这样缩进:
au = 1.49598e11 #astronomical unit in meters
rx = au * np.asarray([.5,.8,.2]) #x-comp separation vector
ry = au * np.asarray([2.6,9.1,3.7]) #y-comp separation vector
rz = au * np.asarray([.05,.1,.25]) #z-comp separation vector
def svec(x,y,z):
'''computes the magnitude and vector components of the distance between two particles.'''
#for loop to compute vector components of separation between two particles
rvec = []
for i in range(3):
if i < 2:
vx = x[i]-x[i+1]
vy = y[i]-y[i+1]
vz = z[i]-z[i+1]
rvec.append([vx,vy,vz])
if i == 2:
vx = x[0]-x[-1]
vy = y[0]-y[-1]
vz = z[0]-z[-1]
rvec.append([vx,vy,vz])
return rvec
comp1 = ['x-comp[m]','y-comp[m]','z-comp[m]']
r0 = rvec[0].insert(0,'particle 0->1')
r1 = rvec[1].insert(0,'particle 1->2')
r2 = rvec[2].insert(0,'particle 0->2')
print(tabulate(rvec,headers=comp1))
代码示例中的缩进似乎不对:您定义了一个函数,但函数主体未缩进。 您是否可以确保粘贴的代码中的缩进与您正在运行的缩进匹配?
这很重要,因为如果您的print
语句在函数的return
语句之后,它将解释为什么什么都不打印。 (与其他语言不同,如果在return
语句后有无法访问的代码,Python不会抱怨。)但是,如果没有看到程序中的实际缩进,我们就无法说出。
编辑:现在,缩进已得到修复,我可以确认return
语句确实会阻止执行之后的所有操作。 也许您打算让return语句后的所有行都缩进去?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.