在for循环中仅打印一次

时间:2017-03-21 00:26:22

标签: python python-3.x for-loop

你好我试图打印下面显示的项目。我只想打印一次,但由于打印报表在for循环内,它们被打印100次。而且我无法取出打印语句,因为里面的值依赖于for循环。关于如何只打印一次这些值的任何想法?

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])

2 个答案:

答案 0 :(得分:1)

选项1:您可以使用下面的其他条件。

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:以下解决方案是使用全局变量

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)

选项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)

答案 1 :(得分:1)

只需在打印上方的行中放置if i == 100:

相关问题