选项1:您可以使用下面这样的else条件。在def Input_Q_bounds(lower, upper):
delta_x = .1
# since there are 100 iterations
J = np.zeros(101)
for i in range(101):
Q_i = (i * delta_x) + (delta_x / 2)
if lower <= Q_i <= upper:
Q = 1
else:
Q = 0
# now fill the matrix
J[i] = (Q + (9.5 * (J[i - 1]))) / 10.5
J_analytical = Q * (np.exp(upper - 10) + (np.exp(lower - 10))
else:
print(J_analytical)
print(J[100])
if __name__ == "__main__":
Input_Q_bounds(lower, upper)
选项2:下面的解决方案是使用全局变量
^{pr2}$
选项3:从函数返回值。在def Input_Q_bounds(lower, upper):
delta_x = .1
# since there are 100 iterations
J = np.zeros(101)
for i in range(101):
Q_i = (i * delta_x) + (delta_x / 2)
if lower <= Q_i <= upper:
Q = 1
else:
Q = 0
# now fill the matrix
J[i] = (Q + (9.5 * (J[i - 1]))) / 10.5
J_analytical = Q * (np.exp(upper - 10) + (np.exp(lower - 10))
return J[100], J_analytical
if __name__ == "__main__":
Input_Q_bounds(lower, upper)