Reputation: 85
Hello I'm trying to print out the items shown below.I only want them printed once but since the print statements are inside the for loop, they are being printed 100 times. and I can't take the print statements out because the values inside are dependent on the for loop. Any ideas on how to print those values only once?
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))
print(J_analytical)
print(J[100])
Upvotes: 0
Views: 4848
Reputation: 1022
Option 1: You can use an else condition like below.
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)
Option 2: The below solution is by using global variables
J_analytical = -1
J = []
def Input_Q_bounds(lower, upper):
global J
global J_analytical
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))
if __name__ == "__main__":
Input_Q_bounds(lower, upper)
print(J[100])
print(J_analytical)
Option 3: Return the values from the function.
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)
Upvotes: 1